// i.r(e), i.d(e, { default: () => SceneModule });

import "regenerator-runtime"
import * as THREE from "three"
import { Collada, ColladaLoader } from "three/examples/jsm/loaders/ColladaLoader"
import { FBXLoader } from "three/examples/jsm/loaders/FBXLoader"
import { GLTF, GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader"
import { MTLLoader } from "three/examples/jsm/loaders/MTLLoader"
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader"
// D.keys().forEach((t) => {
//   B.push(D(t))
// })
// import Z from './---371-88175'
// B.push(Z('./TransformControls.js'))
import { TGALoader } from "three/examples/jsm/loaders/TGALoader"
import RoomMeshData from "../data/RoomMeshData"
import SdkData from "../data/SdkData"
import { SceneChildType } from "../enum/scene.enum"
import { DragBeginEvent, DragEndEvent, DragEvent } from "../event/DragEvent"
import {
  ClickEvent,
  HoverEvent,
  LongPressEndEvent,
  LongPressStartEvent,
  MultiSwipeEndEvent,
  MultiSwipeEvent,
  PinchEndEvent,
  PinchEvent,
  RotateEndEvent,
  RotateEvent,
  UnhoverEvent
} from "../event/GestureEvent"
import { KeyEvent } from "../event/KeyEvent"
import { PointerButtonEvent, PointerMoveEvent } from "../event/PointerEvent"
import { ScrollEvent } from "../event/ScrollEvent"
import ObservableProxy from "../observer/observable.proxy"
import SymbolList from "../SymbolList"
import TransformControls from "../TransformControls"
import blobJS from "../utils/blobJS"
import Comparator from "../utils/Comparator"
import funcUtil from "../utils/func.util"
import imgWork from "../utils/img.work"
import Logger from "../utils/Logger"
import { RequestQueue } from "../utils/request.util"
import { createSubscription } from "../utils/Subscription"
import workUtil from "../utils/work.util"
import AnalyticsModule from "./AnalyticsModule"
import Module from "./Module"
import NavigationModule from "./NavigationModule"
import RaycasterModule from "./RaycasterModule"
var n = {
  CLICK: "INTERACTION.CLICK",
  DRAG: "INTERACTION.DRAG",
  DRAG_BEGIN: "INTERACTION.DRAG_BEGIN",
  DRAG_END: "INTERACTION.DRAG_END",
  HOVER: "INTERACTION.HOVER",
  KEY: "INTERACTION.KEY",
  LONG_PRESS_END: "INTERACTION.LONG_PRESS_END",
  LONG_PRESS_START: "INTERACTION.LONG_PRESS_START",
  MULTI_SWIPE: "INTERACTION.MULTI_SWIPE",
  MULTI_SWIPE_END: "INTERACTION.MULTI_SWIPE_END",
  PINCH: "INTERACTION.PINCH",
  PINCH_END: "INTERACTION.PINCH_END",
  POINTER_BUTTON: "INTERACTION.POINTER_BUTTON",
  POINTER_MOVE: "INTERACTION.POINTER_MOVE",
  ROTATE: "INTERACTION.ROTATE",
  ROTATE_END: "INTERACTION.ROTATE_END",
  SCROLL: "INTERACTION.SCROLL"
}

const l = new Logger("ScenePath")
function h(t, e, i, n) {
  return `${t ? `${t.id}/` : ""}${e.id}/${i}/${n}`
}
function d(t, e, i) {
  switch (((i.node = e), (i.component = null), (i.type = null), (i.property = null), t.length)) {
    case 3:
      ;(i.property = t[2]), (i.component = e.findComponentById(t[0])), (i.type = t[1])
      break
    case 2:
      ;(i.property = t[1]), (i.component = e.findComponentById(t[0])), (i.type = i.component ? p(i.property, i.component) : null)
  }
}
function c(t, e) {
  const i = t.split("/"),
    n = { node: null, component: null, type: null, property: null }
  return d.length > 0 && d(i, e, n), n
}
function u(t, e) {
  const i = t.split("/"),
    n = { node: null, component: null, type: null, property: null }
  if (i.length > 0) {
    const t = e.findNodeById(i[0])
    t && (i.splice(0, 1), d(i, t, n))
  }
  return n
}
function p(t, e) {
  return t in e.outputs ? f.OUTPUT : e.inputs && t in e.inputs ? f.INPUT : t in e.events ? f.EVENT : e.emits && t in e.emits ? f.EMIT : null
}
var f = {
  EMIT: "emit",
  EVENT: "event",
  INPUT: "input",
  OUTPUT: "output"
}

class PathBase {
  id: any
  type: any
  component: any
  node: any
  property: any
  constructor(t) {
    ;(this.id = t.id), (this.type = t.type), (this.component = t.component), (this.node = t.node), (this.property = t.property)
  }
}
class OutputPath extends PathBase {
  output: any
  constructor(t) {
    super(t), (this.output = t.property)
  }
  get() {
    const t = this.component.outputs
    if (t && this.output && t[this.output]) return t[this.output]
    l.warn(`get called on path that does not exist "${this.output}"`)
  }
}
class InputPath extends PathBase {
  input: any
  constructor(t) {
    super(t), (this.input = t.property)
  }
  get() {
    const t = this.component.inputs
    if (t && this.input && this.input in t) return t[this.input]
    l.warn(`get called on component without input "${this.input}`)
  }
  set(t) {
    const e = this.component.inputs
    e && this.input && this.input in e ? (e[this.input] = t) : l.warn(`set called on component without input "${this.input}"`)
  }
}
class EventPath extends PathBase {
  event: any
  constructor(t) {
    super(t), (this.event = t.property)
  }
  get eventName() {
    return this.event
  }
}
class EmitPath extends PathBase {
  emit: any
  constructor(t) {
    super(t), (this.emit = t.property)
  }
  get emitName() {
    return this.emit
  }
}
function _(t) {
  return t.type === f.OUTPUT
}
function m(t) {
  return t.type === f.INPUT
}
function w(t) {
  return t.type === f.EVENT
}
function g(t) {
  return t.type === f.EMIT
}
class IdTracker {
  ids: Set<unknown>
  constructor() {
    this.ids = new Set()
  }
  reserve(t) {
    return !this.ids.has(t) && (this.ids.add(t), !0)
  }
  nextId() {
    let t
    do {
      t = funcUtil.randomStr(4)
    } while (!this.isAvailable(t))
    return this.reserve(t), t
  }
  release(t) {
    this.ids.delete(t)
  }
  isAvailable(t) {
    return !this.ids.has(t)
  }
}
const y = new Logger("SceneComponentFactory")
class ComponentBuilder {
  idTracker: IdTracker
  factories: {}
  constructor() {
    ;(this.idTracker = new IdTracker()), (this.factories = {})
  }
  registerFactory(t, e) {
    return !this.factories[t] && (y.debug(`Component "${t}" registered`), (this.factories[t] = e), !0)
  }
  newInstance(t, e, i, n, s, r) {
    const a = this.factories[t]
    if (!a) throw Error(`Unknown component "${t}"`)
    const o = a()
    return (
      (o.componentType = t),
      ComponentBuilder.setupInputs(o, r),
      ComponentBuilder.setupOutputs(o),
      ComponentBuilder.setupBind(o, this.idTracker, n, s),
      ComponentBuilder.setupEvents(o),
      ComponentBuilder.setupEmits(o),
      ComponentBuilder.setupBindEvent(o, this.idTracker, n, s),
      ComponentBuilder.setupNotify(o, i),
      ComponentBuilder.setupSpyOnEvent(o, this.idTracker, n, s),
      (o.context = e),
      o
    )
  }
  static setupInputs(t, e) {
    if (!t.inputs || 0 === Object.keys(t.inputs).length) return
    t.inputs = ObservableProxy(t.inputs)
    const i = t.inputs
    if (e) for (const t of Object.keys(e)) t in i && (i[t] = e[t])
    for (const t of Object.keys(i)) {
      const e = i[t]
      e && "object" == typeof e && !Array.isArray(e) && (i[t] = ObservableProxy(e))
    }
    return i
  }
  static setupOutputs(t) {
    if (((t.outputs = t.outputs || {}), t.outputs.hasOwnProperty("objectRoot"))) throw Error("outputs.objectRoot is a reserved property of the outputs object")
    if (t.outputs.hasOwnProperty("collider")) throw Error("outputs.collider is a reserved property of the outputs object")
    ;(t.outputs.objectRoot = t.outputs.objectRoot || null), (t.outputs.collider = t.outputs.collider || null), (t.outputs = ObservableProxy(t.outputs))
  }
  static setupBind(t, e, i, n) {
    const s = t.inputs
    t.bind = s
      ? function (r, a, o) {
          if ((y.warn("`SceneComponent.bind` has been deprecated. See `SceneObject.bindPath` for replacement functionality"), !s || !(r in s)))
            throw Error(r + " is not an input of the target component")
          const l = i.addPath({
              id: "input-" + e.nextId(),
              type: f.INPUT,
              node: n,
              component: t,
              property: r
            }),
            h = i.addPath({
              id: "output-" + e.nextId(),
              type: f.OUTPUT,
              node: n,
              component: a,
              property: o
            })
          i.bindPath(l, h)
        }
      : function () {
          throw (
            (y.warn("`SceneComponent.bind` has been deprecated. See `SceneObject.bindPath` for replacement functionality"),
            Error("This component has no inputs, bind failed"))
          )
        }
  }
  static setupEvents(t) {
    const e = t.events || {}
    for (const i of Object.values(n)) e[i] = !!e[i]
    t.events = ObservableProxy(e)
  }
  static setupEmits(t) {
    const e = t.emits
    e && Object.keys(e).length > 0 && (t.emits = ObservableProxy(e))
  }
  static setupBindEvent(t, e, i, n) {
    t.bindEvent = function (s, r, a) {
      if ((y.warn("`SceneComponent.bindEvent` has been deprecated. See `SceneObject.bindPath` for replacement functionality"), !(s in t.events)))
        throw Error(s + " is not supported by the target component")
      const o = i.addPath({
        id: "event-" + e.nextId(),
        type: f.EVENT,
        node: n,
        component: t,
        property: s
      })
      v(r, a)
      const l = i.addPath({
        id: "emit-" + e.nextId(),
        type: f.EMIT,
        node: n,
        component: r,
        property: a
      })
      i.bindPath(o, l)
    }
  }
  static setupNotify(t, e) {
    t.notify = function (i, n) {
      ;(t.emits && !t.emits[i]) || e.notify(t, { type: i, data: n })
    }
  }
  static setupSpyOnEvent(t, e, i, n) {
    t.spyOnEvent = function (s) {
      y.warn("`SceneComponent.spyOnEvent` has been deprecated. See `SceneObject.spyOnEvent` for replacement functionality"), v(t, s.eventType)
      const r = i.addPath({
        id: "event-spy-" + e.nextId(),
        type: f.EMIT,
        node: n,
        component: t,
        property: s.eventType
      })
      return i.spyOnEvent({ path: r, onEvent: s.onEvent.bind(s) })
    }
  }
}
function v(t, e) {
  const i = t.emits
  ;(i && i.isObservableProxy) || ((t.emits = i || {}), (t.emits[e] = !0))
}
class ComponentEventBus {
  observers: Map<any, any>
  constructor() {
    this.observers = new Map()
  }
  notify(t, e) {
    const i = this.observers.get(t)
    if (i) {
      const t = i.get(e.type)
      if (t) for (const i of t) i.onEvent(i.targetEventType, e.data)
    }
  }
  observe(t) {
    const e = this.observers.get(t.src) || new Map()
    this.observers.set(t.src, e)
    const i = e.get(t.srcEventType) || new Set()
    e.set(t.srcEventType, i), i.add(t)
    const n = this
    return {
      cancel() {
        n.removeObserver(t)
      }
    }
  }
  removeObserver(t) {
    const { src: e, srcEventType: i } = t,
      n = this.observers.get(e)
    if (n) {
      const e = n.get(i)
      e && e.delete(t)
    }
  }
}
class CwfComponent {
  instance: any
  onBeforeRender: any
  analytics: any
  state: any
  inputsCache: any
  dirty: boolean
  interactionQueue: any[]
  constructor(t, e, i) {
    ;(this.instance = t),
      (this.onBeforeRender = e),
      (this.analytics = i),
      (this.state = null),
      (this.inputsCache = null),
      (this.dirty = !1),
      (this.interactionQueue = []),
      (this.onDataChanged = this.onDataChanged.bind(this))
  }
  init() {}
  beforeRender(t) {
    if ((this.onBeforeRender.update(), this.instance.onEvent))
      for (; this.interactionQueue.length > 0; ) {
        const t = this.interactionQueue.shift()
        t && this.instance.onEvent(t.type, t.data)
      }
    this.dirty &&
      this.instance.onInputsUpdated &&
      this.inputsCache &&
      (this.instance.onInputsUpdated(this.inputsCache), Object.assign(this.inputsCache, this.instance.inputs), (this.dirty = !1)),
      this.instance.onTick && this.instance.onTick(t)
  }
  render(t) {}
  dispose() {
    this.state && this.state.removeOnChanged(this.onDataChanged)
  }
  activate() {
    const t = this.instance.inputs
    t && (t.onChanged(this.onDataChanged), (this.inputsCache = Object.assign({}, t))), this.instance.onInit && this.instance.onInit()
    const e = { componentType: this.instance.componentType }
    this.analytics.track("sdk_component_start", this.instance.componentType, e)
  }
  deactivate() {
    const t = this.instance.inputs
    t && t.removeOnChanged(this.onDataChanged), this.instance.onDestroy && this.instance.onDestroy()
  }
  onDataChanged() {
    this.dirty = !0
  }
  onEvent(t) {
    this.interactionQueue.push(t)
  }
}
class ProxyFactory {
  propertyAccessor: any
  constructor(t) {
    this.propertyAccessor = t
  }
  create(t, e) {
    return this._createProxy(t, i => {
      const n = this.propertyAccessor
      return {
        get: () => (n.onAccess(e, i), t[i]),
        set: s => (n.onAccess(e, i), (t[i] = s), s)
      }
    })
  }
  createReadonly(t, e) {
    return this._createProxy(t, i => {
      const n = this.propertyAccessor
      return { get: () => (n.onAccess(e, i), t[i]) }
    })
  }
  _createProxy(t, e) {
    const i = {}
    for (const n in t) t.hasOwnProperty(n) && Object.defineProperty(i, n, e(n))
    return i
  }
}
const T = new Logger("SceneNode")
var j = {
  0: "Idle",
  1: "Operating",
  2: "Stopped",
  Idle: 0,
  Operating: 1,
  Stopped: 2
}

class SceneNode {
  componentLoader: any
  renderer: any
  targets: any
  analytics: any
  componentFactory: any
  sceneObject: any
  eventBus: any
  inputIni: any
  sceneNodeFactory: any
  obj3D: THREE.Object3D
  state: any
  components: any[]
  interactionsSubs: any[]
  idTracker: IdTracker
  proxyFactory: ProxyFactory
  id: any
  static inputEventMap: any
  constructor(t, e, i, n, s, r, a, o, l, h) {
    ;(this.componentLoader = t),
      (this.renderer = e),
      (this.targets = i),
      (this.analytics = n),
      (this.componentFactory = s),
      (this.sceneObject = r),
      (this.eventBus = a),
      (this.inputIni = o),
      (this.sceneNodeFactory = h),
      (this.obj3D = new THREE.Object3D()),
      (this.state = j.Idle),
      (this.components = []),
      (this.interactionsSubs = []),
      (this.idTracker = new IdTracker()),
      (this.proxyFactory = new ProxyFactory(l))
  }
  *componentIterator() {
    for (const t of this.components) yield t.instance
  }
  *bindings() {
    for (const t of this.sceneObject.bindings()) {
      const [e] = t
      e.node.id === this.id && (yield t)
    }
  }
  findComponentById(t) {
    const e = this.components.find(e => e.instance.id === t)
    return e ? e.instance : null
  }
  addObject(t) {
    return this.obj3D.add(t), t
  }
  removeObject(t) {
    this.obj3D.remove(t)
  }
  addCollider(t) {
    this.targets.addTarget(t, !1)
    return t
  }
  removeCollider(t) {
    this.targets.removeTarget(t)
  }
  get name() {
    return this.obj3D.name || ""
  }
  set name(t) {
    this.obj3D.name = t
  }
  get position() {
    return this.obj3D.position
  }
  get quaternion() {
    return this.obj3D.quaternion
  }
  get scale() {
    return this.obj3D.scale
  }
  addComponent(t, e, i) {
    if (this.state !== j.Idle) return T.warn("Cannot add component after the node has started"), null
    const n = {
      three: this.proxyFactory.createReadonly(THREE, "three"),
      renderer: this.proxyFactory.create(this.renderer.cwfRenderer.renderer, "renderer"),
      scene: this.renderer.getScene().scene,
      camera: this.renderer.getScene().camera,
      nodeFactory: this.sceneNodeFactory,
      root: this
    }
    const s = this.componentFactory.newInstance(t, n, this.eventBus, this.sceneObject, this, e),
      r = new CwfComponent(
        s,
        new (class MatrixWorldUpdater {
          sceneNode: any
          constructor(t) {
            this.sceneNode = t
          }
          update() {
            this.sceneNode.obj3D.updateMatrixWorld()
          }
        })(this),
        this.analytics
      )
    this.components.push(r)
    const a = s.outputs
    this.subscribeToObjectOutput(a)
    const o = this.subscribeToInteraction(r, s)
    if ((this.interactionsSubs.push(o), i)) {
      if (!this.idTracker.isAvailable(i)) throw Error("Component with duplicate id detected.")
      if (-1 !== i.indexOf("/")) throw Error('Component ids cannot have "/" character.')
      this.idTracker.reserve(i)
    }
    const l = i || this.idTracker.nextId()
    return (
      Object.defineProperty(s, "id", {
        value: l,
        writable: !1,
        enumerable: !0
      }),
      s
    )
  }
  subscribeToObjectOutput(t) {
    let e
    t.onPropertyChanged("objectRoot", () => {
      e && (this.removeObject(e), (e = void 0)),
        t.objectRoot instanceof THREE.Object3D
          ? (e = this.addObject(t.objectRoot))
          : t.objectRoot && T.warn("outputs.object is not an instanceof THREE.Object3D")
    })
  }
  subscribeToInteraction(t, e) {
    let i, s
    const r = e.outputs,
      a = () => {
        if ((i && (this.removeCollider(i), (i = void 0)), s)) {
          for (const t of s) t.cancel()
          s = void 0
        }
      },
      o = () => {
        a(),
          r.collider instanceof THREE.Object3D
            ? ((i = this.addCollider(r.collider)), (s = this.registerInput(t, r.collider, e.events)))
            : r.collider && T.warn("outputs.collider is not an instanceof THREE.Object3D")
      }
    return (
      e.events.onPropertyChanged(n.CLICK, o),
      e.events.onPropertyChanged(n.HOVER, o),
      e.events.onPropertyChanged(n.DRAG, o),
      r.onPropertyChanged("collider", o),
      createSubscription(
        () => {},
        () => a()
      )
    )
  }
  registerInput(t, e, i) {
    const s = (e, i, n, s) => {
        const r = SceneNode.inputEventMap.get(Object.getPrototypeOf(e).constructor)
        if (r) {
          const a = {
            type: r,
            data: Object.assign(s || {}, {
              collider: i,
              point: n ? n.point : null,
              normal: n && n.face ? n.face.normal : null,
              input: e
            })
          }
          t.onEvent(a)
        }
      },
      r = Comparator.is(t => (t === e && t.visible) || L(e)(t)),
      a = []
    return (
      i[n.CLICK] && a.push(this.inputIni.registerMeshHandler(ClickEvent, r, s)),
      i[n.HOVER] &&
        a.push(
          this.inputIni.registerMeshHandler(HoverEvent, r, (t, e, i) => {
            s(t, e, i, { hover: !0 })
          }),
          this.inputIni.registerMeshHandler(UnhoverEvent, r, (t, e, i) => {
            s(t, e, i, { hover: !1 })
          })
        ),
      i[n.DRAG] &&
        a.push(
          this.inputIni.registerMeshHandler(DragBeginEvent, r, s),
          this.inputIni.registerMeshHandler(DragEvent, r, s),
          this.inputIni.registerMeshHandler(DragEndEvent, r, s)
        ),
      a
    )
  }
  start() {
    if (this.state === j.Idle) {
      this.obj3D.parent || this.renderer.getScene().addChild(SceneChildType.Root, this.obj3D)
      for (const t of this.components) this.componentLoader.addComponent(t)
      this.state = j.Operating
    }
  }
  stop() {
    if (this.state === j.Operating) {
      for (const t of this.interactionsSubs) t.cancel()
      this.interactionsSubs = []
      for (const t of this.components) this.componentLoader.removeComponent(t)
      this.obj3D.parent && this.obj3D.parent.remove(this.obj3D), (this.state = j.Stopped)
    }
  }
}
SceneNode.inputEventMap = new Map<any, any>([
  [ClickEvent, n.CLICK],
  [HoverEvent, n.HOVER],
  [UnhoverEvent, n.HOVER],
  [DragEvent, n.DRAG],
  [DragBeginEvent, n.DRAG_BEGIN],
  [DragEndEvent, n.DRAG_END]
])
const L = t => e => {
  for (let i = e; i; i = i.parent) {
    if (!i.visible) return !1
    if (t === i.parent) return !0
  }
  return !1
}
class OBJLoader2Component {
  static factoryName: string
  async load(t, e) {
    let i = null
    if (e) {
      const t = new MTLLoader()
      i = await ((n = t),
      (s = e),
      new Promise((t, e) => {
        n.load(
          s,
          function (e) {
            t(e)
          },
          void 0,
          e
        )
      }))
    }
    var n, s
    const r = new OBJLoader()
    i && r.setMaterials(i)
    const a: any = await ((t, e) =>
      new Promise((i, n) => {
        t.load(
          e,
          function (t) {
            i(t)
          },
          void 0,
          n
        )
      }))(r, t)
    return (
      a.traverse(t => {
        if ("Mesh" === t.type) {
          const e = t
          ;(e.castShadow = !0), (e.receiveShadow = !0)
        }
      }),
      { objectRoot: a, collider: a }
    )
  }
}
OBJLoader2Component.factoryName = "mp.objLoader"
class FBXLoaderComponent {
  static factoryName: string
  async load(t, e) {
    const i = new FBXLoader(),
      //@ts-ignore
      n: THREE.Group = await ((t, e) =>
        new Promise((i, n) => {
          t.load(
            e,
            t => {
              i(t)
            },
            void 0,
            n
          )
        }))(i, t)
    return (
      n.traverse(t => {
        if ("Mesh" === t.type) {
          const e = t
          ;(e.castShadow = !0), (e.receiveShadow = !0)
        }
      }),
      { objectRoot: n, collider: n }
    )
  }
}
FBXLoaderComponent.factoryName = "mp.fbxLoader"
class ColladaLoaderComponent {
  static factoryName: string
  async load(t, e) {
    const i = new ColladaLoader(),
      //@ts-ignore
      n: Collada = await ((t, e) =>
        new Promise((i, n) => {
          t.load(
            e,
            function (t) {
              i(t)
            },
            void 0,
            n
          )
        }))(i, t)
    return (
      n.scene.traverse(t => {
        if ("Mesh" === t.type) {
          const e = t
          ;(e.castShadow = !0), (e.receiveShadow = !0)
        }
      }),
      { objectRoot: n.scene, collider: n.scene }
    )
  }
}
ColladaLoaderComponent.factoryName = "mp.daeLoader"
class GLTFLoaderComponent {
  static factoryName: string
  async load(t, e) {
    const i = new GLTFLoader(),
      //@ts-ignore
      n: GLTF = await ((t, e) =>
        new Promise((i, n) => {
          t.load(
            e,
            t => {
              i(t)
            },
            void 0,
            n
          )
        }))(i, t)
    return (
      n.scene.traverse(t => {
        if ("Mesh" === t.type) {
          const e = t
          ;(e.castShadow = !0), (e.receiveShadow = !0)
        }
      }),
      { objectRoot: n.scene, collider: n.scene }
    )
  }
}
GLTFLoaderComponent.factoryName = "mp.gltfLoader"

var N = {
  Rotate: "rotate",
  Translate: "translate",
  scale: "scale"
}

class TransformControlsComponent {
  controlsSubs: any[]
  inputs: { visible: boolean; selection: any; mode: any; showX: boolean; showY: boolean; showZ: boolean; size: number }
  events: { [x: number]: boolean }
  transformControls: TransformControls
  context: any
  outputs: any
  collider: any
  static factory: () => TransformControlsComponent
  static factoryName: string
  constructor() {
    ;(this.controlsSubs = []),
      (this.inputs = {
        visible: !0,
        selection: null,
        mode: N.Translate,
        showX: !0,
        showY: !0,
        showZ: !0,
        size: 1
      }),
      (this.events = { [n.HOVER]: !1, [n.DRAG]: !0, [n.CLICK]: !1 })
  }
  onInit() {
    this.transformControls = new TransformControls(this.context.camera, this.context.renderer.domElement)
    this.transformControls.enabled = !0
    this.outputs.objectRoot = this.transformControls
    this.collider = this.transformControls.children[0]
    this.onInputsUpdated()
  }
  onEvent() {}
  onInputsUpdated() {
    if (this.inputs.selection) {
      const t = this.inputs.selection.obj3D
      this.transformControls.attach(t), (this.outputs.collider = this.collider)
    } else this.transformControls.detach(), (this.outputs.collider = null)
    this.handleMode()
  }
  onDestroy() {
    for (const t of this.controlsSubs) t.cancel()
    ;(this.outputs.objectRoot = null), this.transformControls.dispose()
  }
  handleMode() {
    this.transformControls.mode !== this.inputs.mode && this.transformControls.setMode(this.inputs.mode)
    this.transformControls.showX = this.inputs.showX
    this.transformControls.showY = this.inputs.showY
    this.transformControls.showZ = this.inputs.showZ
    this.transformControls.size = this.inputs.size
  }
}
TransformControlsComponent.factory = () => new TransformControlsComponent()
TransformControlsComponent.factoryName = "mp.transformControls"
// import D from './---371-90321'
var B = []

class ScrollingTube {
  visibleCache: boolean
  lengthCache: number
  radiusCache: number
  fillColorCache: string
  textColorCache: string
  textCache: string
  fontCache: string
  mesh: any
  material: any
  geometry: any
  texture: any
  time: number
  inputs: { visible: boolean; length: number; radius: number; fillColor: string; textColor: string; text: string; font: string; scrollSpeed: number }
  outputs: any
  static factory: () => ScrollingTube
  static factoryName: string
  constructor() {
    ;(this.visibleCache = !0),
      (this.lengthCache = 1),
      (this.radiusCache = 0.5),
      (this.fillColorCache = "rgba(0,255,0,0.3)"),
      (this.textColorCache = "rgb(0,255,0)"),
      (this.textCache = "➡︎"),
      (this.fontCache = "48px sans-serif"),
      (this.mesh = null),
      (this.material = null),
      (this.geometry = null),
      (this.texture = null),
      (this.time = 0),
      (this.inputs = {
        visible: !0,
        length: 1,
        radius: 0.5,
        fillColor: "rgba(0,255,0,0.3)",
        textColor: "rgb(255,255,255)",
        text: "➡︎",
        font: "48px sans-serif",
        scrollSpeed: 1
      })
  }
  onInit() {
    this.updateCache(), this.makeTube()
  }
  onInputsUpdated() {
    ;(this.inputs.length === this.lengthCache &&
      this.inputs.radius === this.radiusCache &&
      this.inputs.fillColor === this.fillColorCache &&
      this.inputs.textColor === this.textColorCache &&
      this.inputs.text === this.textCache &&
      this.inputs.font === this.fontCache) ||
      (this.updateCache(), this.makeTube()),
      this.visibleCache !== this.inputs.visible && ((this.visibleCache = this.inputs.visible), this.mesh && (this.mesh.visible = this.inputs.visible))
  }
  onDestroy() {
    this.releaseTube()
  }
  updateCache() {
    ;(this.radiusCache = this.inputs.radius),
      (this.lengthCache = this.inputs.length),
      (this.fillColorCache = this.inputs.fillColor),
      (this.textColorCache = this.inputs.textColor),
      (this.textCache = this.inputs.text),
      (this.fontCache = this.inputs.font)
  }
  makeTube() {
    this.releaseTube()
    const t = document.createElement("canvas").getContext("2d")
    if (!t) return
    ;(t.canvas.width = 64),
      (t.canvas.height = 64),
      (t.fillStyle = this.inputs.fillColor),
      t.fillRect(0, 0, 64, 64),
      t.translate(32, 32),
      t.rotate(0.5 * Math.PI),
      (t.fillStyle = this.inputs.textColor),
      (t.textAlign = "center"),
      (t.textBaseline = "middle"),
      (t.font = this.inputs.font),
      t.fillText(this.inputs.text, 0, 0),
      (this.texture = new THREE.CanvasTexture(t.canvas)),
      (this.texture.wrapS = THREE.RepeatWrapping),
      (this.texture.wrapT = THREE.RepeatWrapping),
      (this.texture.repeat.x = 4),
      (this.texture.repeat.y = this.inputs.length / (2 * this.inputs.radius))
    const e = new THREE.CylinderBufferGeometry(this.inputs.radius, this.inputs.radius, this.inputs.length, 20, 2, !0)
    ;(this.material = new THREE.MeshBasicMaterial({
      map: this.texture,
      depthWrite: !1,
      depthTest: !1,
      transparent: !0
    })),
      (this.outputs.objectRoot = new THREE.Mesh(e, this.material))
  }
  onTick(t) {
    ;(this.time += t), this.texture && (this.texture.offset.y = ((this.inputs.scrollSpeed * this.time) / 1e3) % 1)
  }
  releaseTube() {
    this.material && (this.material.dispose(), (this.material = null)),
      this.geometry && (this.geometry.dispose(), (this.geometry = null)),
      this.texture && (this.texture.dispose(), (this.texture = null)),
      (this.mesh = null)
  }
}
;(ScrollingTube.factory = () => new ScrollingTube()), (ScrollingTube.factoryName = "mp.scrollingTube")

var G = {
  Floor: "floor",
  Model: "model",
  Room: "room",
  Scene: "scene"
}

class Tags {
  tagMap: Map<any, any>
  tmpSet: Set<unknown>
  constructor() {
    ;(this.tagMap = new Map()), (this.tmpSet = new Set())
  }
  tagObject(t, e) {
    for (const i of e) {
      let e = this.tagMap.get(i)
      e || ((e = []), this.tagMap.set(i, e))
      e.find(e => e === t) || e.push(t)
    }
  }
  untagObject(t, e) {
    for (const i of e) {
      const e = this.tagMap.get(i)
      if (e) {
        const i = e.findIndex(e => e === t)
        ;-1 !== i && e.splice(i)
      }
    }
  }
  getObjects(t) {
    this.tmpSet.clear()
    const e = []
    for (const i of t) {
      const t = this.tagMap.get(i)
      if (t) for (const i of t) this.tmpSet.has(i) || (e.push(i), this.tmpSet.add(i))
    }
    return e
  }
}
class LightsComponents {
  outputs: any
  static factory: () => LightsComponents
  static factoryName: string
  onInit() {
    const t = new THREE.Object3D(),
      e = new THREE.AmbientLight(8947848),
      i = new THREE.DirectionalLight(14540253, 1)
    i.position.set(1, 0.5, 1), t.add(e), t.add(i), (this.outputs.objectRoot = t)
  }
}
;(LightsComponents.factory = () => new LightsComponents()), (LightsComponents.factoryName = "mp.lights")
class PointLightComponent {
  inputs: {
    enabled: boolean
    color: { r: number; g: number; b: number }
    intensity: number
    position: { x: number; y: number; z: number }
    distance: number
    decay: number
    castShadow: boolean
    debug: boolean
  }
  light: THREE.PointLight
  lightHelper: THREE.PointLightHelper
  outputs: any
  static factory: () => PointLightComponent
  static factoryName: string
  constructor() {
    this.inputs = {
      enabled: !0,
      color: { r: 1, g: 1, b: 1 },
      intensity: 2,
      position: { x: 1, y: 5, z: 1 },
      distance: 0,
      decay: 1,
      castShadow: !1,
      debug: !1
    }
  }
  onInit() {
    ;(this.light = new THREE.PointLight()), (this.lightHelper = new THREE.PointLightHelper(this.light, 1))
    const t = new THREE.Group()
    t.add(this.light), t.add(this.lightHelper), this.onInputsUpdated(), (this.outputs.objectRoot = t)
  }
  onInputsUpdated() {
    ;(this.light.visible = this.inputs.enabled),
      (this.lightHelper.visible = this.inputs.debug),
      this.light.visible &&
        (this.light.position.set(this.inputs.position.x, this.inputs.position.y, this.inputs.position.z),
        this.light.color.setRGB(this.inputs.color.r, this.inputs.color.g, this.inputs.color.b),
        (this.light.intensity = this.inputs.intensity),
        (this.light.distance = this.inputs.distance),
        (this.light.decay = this.inputs.decay),
        (this.light.castShadow = this.inputs.castShadow))
  }
  onDestroyed() {
    this.lightHelper.dispose(), (this.outputs.objectRoot = null)
  }
  onTick() {
    this.inputs.debug && this.lightHelper.update()
  }
}

PointLightComponent.factory = () => new PointLightComponent()
PointLightComponent.factoryName = "mp.pointLight"
class DirectionalLightComponent {
  inputs: {
    enabled: boolean
    color: { r: number; g: number; b: number }
    intensity: number
    position: { x: number; y: number; z: number }
    target: { x: number; y: number; z: number }
    castShadow: boolean
    debug: boolean
  }
  targetObject: THREE.Object3D
  light: THREE.DirectionalLight
  lightHelper: THREE.DirectionalLightHelper
  outputs: any
  static factory: () => DirectionalLightComponent
  static factoryName: string
  constructor() {
    this.inputs = {
      enabled: !0,
      color: { r: 1, g: 1, b: 1 },
      intensity: 2,
      position: { x: 1, y: 5, z: 1 },
      target: { x: 0, y: 0, z: 0 },
      castShadow: !1,
      debug: !1
    }
  }
  onInit() {
    ;(this.targetObject = new THREE.Object3D()),
      (this.light = new THREE.DirectionalLight()),
      (this.light.target = this.targetObject),
      (this.light.castShadow = !0),
      (this.lightHelper = new THREE.DirectionalLightHelper(this.light, 1))
    const t = new THREE.Group()
    t.add(this.light), t.add(this.targetObject), t.add(this.lightHelper), this.onInputsUpdated(), (this.outputs.objectRoot = t)
  }
  onInputsUpdated(t = null) {
    ;(this.light.visible = this.inputs.enabled),
      (this.lightHelper.visible = this.inputs.debug),
      this.inputs.enabled &&
        (this.targetObject.position.set(this.inputs.target.x, this.inputs.target.y, this.inputs.target.z),
        this.light.position.set(this.inputs.position.x, this.inputs.position.y, this.inputs.position.z),
        this.light.color.setRGB(this.inputs.color.r, this.inputs.color.g, this.inputs.color.b),
        (this.light.intensity = this.inputs.intensity),
        (this.light.castShadow = this.inputs.castShadow))
  }
  onTick(t) {
    this.inputs.debug && this.lightHelper.update()
  }
  onDestroyed() {
    this.lightHelper.dispose(), (this.outputs.objectRoot = null)
  }
}
;(DirectionalLightComponent.factory = () => new DirectionalLightComponent()), (DirectionalLightComponent.factoryName = "mp.directionalLight")
class AmbientLightComponent {
  inputs: { enabled: boolean; color: { r: number; g: number; b: number }; intensity: number }
  light: THREE.AmbientLight
  outputs: any
  static factory: () => AmbientLightComponent
  static factoryName: string
  constructor() {
    this.inputs = {
      enabled: !0,
      color: { r: 0.2, g: 0.2, b: 0.2 },
      intensity: 1
    }
  }
  onInit() {
    ;(this.light = new THREE.AmbientLight()), this.onInputsUpdated(), (this.outputs.objectRoot = this.light)
  }
  onInputsUpdated() {
    this.light.color.setRGB(this.inputs.color.r, this.inputs.color.g, this.inputs.color.b),
      (this.light.intensity = this.inputs.intensity),
      (this.light.visible = this.inputs.enabled)
  }
  onDestroyed() {
    this.outputs.objectRoot = null
  }
}
;(AmbientLightComponent.factory = () => new AmbientLightComponent()), (AmbientLightComponent.factoryName = "mp.ambientLight")
class SceneAnalytics {
  analytics: any
  sdkData: any
  track: (t: any, e: any) => Promise<void>
  constructor(t, e) {
    ;(this.analytics = t),
      (this.sdkData = e),
      (this.track = async (t, e) => {
        const i = Object.assign(e || {}, {
          applicationKey: this.sdkData.applicationKey
        })
        this.analytics.track(t, i)
      })
  }
}
class TrackFirstPropertyAnalyticsWrapper {
  analytics: any
  trackedProperties: {}
  constructor(t) {
    ;(this.analytics = t), (this.trackedProperties = {})
  }
  onAccess(t, e) {
    if (this.trackedProperties[String(e)]) return
    this.trackedProperties[String(e)] = !0
    const i = { name: t, property: e }
    this.analytics.track("context-usage", i)
  }
}
class TrackFirstKeyAnalytics {
  analytics: any
  trackedKeys: {}
  constructor(t) {
    ;(this.analytics = t), (this.trackedKeys = {})
  }
  track(t, e, i) {
    this.trackedKeys[String(e)] || ((this.trackedKeys[String(e)] = !0), this.analytics.track(t, i))
  }
}

class ImageLoader extends THREE.Loader {
  renderer: any
  requestq: RequestQueue
  worker: any
  constructor(t, e) {
    super(), (this.renderer = t), (this.requestq = new RequestQueue()), (this.worker = e())
  }
  load(t, e) {
    const i = new THREE.Texture()
    return (
      this.requestImage(t).then(async t => {
        this.updateTexture(i, t), e && e(i)
      }),
      i
    )
  }
  async loadAsync(t) {
    const e = await this.requestImage(t),
      i = await this.worker.exec(e, [e]),
      n = new THREE.DataTexture(new Uint8ClampedArray(i.width), i.width, i.height)
    return (n.format = this.getPixelFormat(i)), this.prerenderTexture(n), n
  }
  requestImage(t) {
    return this.requestq.get(t, { responseType: "arraybuffer" })
  }
  async updateTexture(t, e) {
    const i = await this.worker.exec(e, [e])
    ;(t.format = this.getPixelFormat(i)),
      (function (t, e) {
        ;(t.image = {
          data: new Uint8Array(e.data),
          height: e.height,
          width: e.width
        }),
          (t.isDataTexture = !0)
      })(t, i),
      this.prerenderTexture(t)
  }
  getPixelFormat(t) {
    const e = t.data.byteLength / (t.width * t.height)
    if (4 === e) return THREE.RGBAFormat
    if (3 === e) return THREE.RGBFormat
    if (1 === e) return THREE.AlphaFormat
    throw Error("images with only 2 channels are not supported")
  }
  prerenderTexture(t) {
    ;(t.needsUpdate = !0), this.renderer.initTexture(t), (t.image = new ImageData(1, 1))
  }
}
let K = null
function Q(t) {
  return function () {
    return (function (t) {
      return K || (K = new ImageLoader(t, imgWork.createJpegDecodeWorker)), K
    })(t)
  }
}

const tt = workUtil.createWork(function () {
  return blobJS()(
    '(()=>{"use strict";var t={396:function(){!function(t){if(t.TextEncoder&&t.TextDecoder)return!1;function e(t="utf-8"){if("utf-8"!==t)throw new RangeError(`Failed to construct \'TextEncoder\': The encoding label provided (\'${t}\') is invalid.`)}function i(t="utf-8",e={fatal:!1}){if("utf-8"!==t)throw new RangeError(`Failed to construct \'TextDecoder\': The encoding label provided (\'${t}\') is invalid.`);if(e.fatal)throw new Error("Failed to construct \'TextDecoder\': the \'fatal\' option is unsupported.")}Object.defineProperty(e.prototype,"encoding",{value:"utf-8"}),e.prototype.encode=function(t,e={stream:!1}){if(e.stream)throw new Error("Failed to encode: the \'stream\' option is unsupported.");let i=0;const a=t.length;let n=0,s=Math.max(32,a+(a>>1)+7),r=new Uint8Array(s>>3<<3);for(;i<a;){let e=t.charCodeAt(i++);if(e>=55296&&e<=56319){if(i<a){const a=t.charCodeAt(i);56320==(64512&a)&&(++i,e=((1023&e)<<10)+(1023&a)+65536)}if(e>=55296&&e<=56319)continue}if(n+4>r.length){s+=8,s*=1+i/t.length*2,s=s>>3<<3;const e=new Uint8Array(s);e.set(r),r=e}if(0!=(4294967168&e)){if(0==(4294965248&e))r[n++]=e>>6&31|192;else if(0==(4294901760&e))r[n++]=e>>12&15|224,r[n++]=e>>6&63|128;else{if(0!=(4292870144&e))continue;r[n++]=e>>18&7|240,r[n++]=e>>12&63|128,r[n++]=e>>6&63|128}r[n++]=63&e|128}else r[n++]=e}return r.slice(0,n)},Object.defineProperty(i.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(i.prototype,"fatal",{value:!1}),Object.defineProperty(i.prototype,"ignoreBOM",{value:!1}),i.prototype.decode=function(t,e={stream:!1}){if(e.stream)throw new Error("Failed to decode: the \'stream\' option is unsupported.");const i=new Uint8Array(t);let a=0;const n=i.length,s=[];for(;a<n;){const t=i[a++];if(0===t)break;if(0==(128&t))s.push(t);else if(192==(224&t)){const e=63&i[a++];s.push((31&t)<<6|e)}else if(224==(240&t)){const e=63&i[a++],n=63&i[a++];s.push((31&t)<<12|e<<6|n)}else if(240==(248&t)){let e=(7&t)<<18|(63&i[a++])<<12|(63&i[a++])<<6|63&i[a++];e>65535&&(e-=65536,s.push(e>>>10&1023|55296),e=56320|1023&e),s.push(e)}}return String.fromCharCode.apply(null,s)},t.TextEncoder=e,t.TextDecoder=i}("undefined"!=typeof window?window:"undefined"!=typeof self?self:this)}},e={};function i(a){var n=e[a];if(void 0!==n)return n.exports;var s=e[a]={exports:{}};return t[a].call(s.exports,s,s.exports,i),s.exports}(()=>{i(396);const t=new TextDecoder("utf-8");const e=new TextEncoder;class IOBuffer_IOBuffer{constructor(t=8192,e={}){let i=!1;"number"==typeof t?t=new ArrayBuffer(t):(i=!0,this.lastWrittenByte=t.byteLength);const a=e.offset?e.offset>>>0:0,n=t.byteLength-a;let s=a;(ArrayBuffer.isView(t)||t instanceof IOBuffer_IOBuffer)&&(t.byteLength!==t.buffer.byteLength&&(s=t.byteOffset+a),t=t.buffer),this.lastWrittenByte=i?n:0,this.buffer=t,this.length=n,this.byteLength=n,this.byteOffset=s,this.offset=0,this.littleEndian=!0,this._data=new DataView(this.buffer,s,n),this._mark=0,this._marks=[]}available(t=1){return this.offset+t<=this.length}isLittleEndian(){return this.littleEndian}setLittleEndian(){return this.littleEndian=!0,this}isBigEndian(){return!this.littleEndian}setBigEndian(){return this.littleEndian=!1,this}skip(t=1){return this.offset+=t,this}seek(t){return this.offset=t,this}mark(){return this._mark=this.offset,this}reset(){return this.offset=this._mark,this}pushMark(){return this._marks.push(this.offset),this}popMark(){const t=this._marks.pop();if(void 0===t)throw new Error("Mark stack empty");return this.seek(t),this}rewind(){return this.offset=0,this}ensureAvailable(t=1){if(!this.available(t)){const e=2*(this.offset+t),i=new Uint8Array(e);i.set(new Uint8Array(this.buffer)),this.buffer=i.buffer,this.length=this.byteLength=e,this._data=new DataView(this.buffer)}return this}readBoolean(){return 0!==this.readUint8()}readInt8(){return this._data.getInt8(this.offset++)}readUint8(){return this._data.getUint8(this.offset++)}readByte(){return this.readUint8()}readBytes(t=1){const e=new Uint8Array(t);for(let i=0;i<t;i++)e[i]=this.readByte();return e}readInt16(){const t=this._data.getInt16(this.offset,this.littleEndian);return this.offset+=2,t}readUint16(){const t=this._data.getUint16(this.offset,this.littleEndian);return this.offset+=2,t}readInt32(){const t=this._data.getInt32(this.offset,this.littleEndian);return this.offset+=4,t}readUint32(){const t=this._data.getUint32(this.offset,this.littleEndian);return this.offset+=4,t}readFloat32(){const t=this._data.getFloat32(this.offset,this.littleEndian);return this.offset+=4,t}readFloat64(){const t=this._data.getFloat64(this.offset,this.littleEndian);return this.offset+=8,t}readChar(){return String.fromCharCode(this.readInt8())}readChars(t=1){let e="";for(let i=0;i<t;i++)e+=this.readChar();return e}readUtf8(e=1){return i=this.readBytes(e),t.decode(i);var i}writeBoolean(t){return this.writeUint8(t?255:0),this}writeInt8(t){return this.ensureAvailable(1),this._data.setInt8(this.offset++,t),this._updateLastWrittenByte(),this}writeUint8(t){return this.ensureAvailable(1),this._data.setUint8(this.offset++,t),this._updateLastWrittenByte(),this}writeByte(t){return this.writeUint8(t)}writeBytes(t){this.ensureAvailable(t.length);for(let e=0;e<t.length;e++)this._data.setUint8(this.offset++,t[e]);return this._updateLastWrittenByte(),this}writeInt16(t){return this.ensureAvailable(2),this._data.setInt16(this.offset,t,this.littleEndian),this.offset+=2,this._updateLastWrittenByte(),this}writeUint16(t){return this.ensureAvailable(2),this._data.setUint16(this.offset,t,this.littleEndian),this.offset+=2,this._updateLastWrittenByte(),this}writeInt32(t){return this.ensureAvailable(4),this._data.setInt32(this.offset,t,this.littleEndian),this.offset+=4,this._updateLastWrittenByte(),this}writeUint32(t){return this.ensureAvailable(4),this._data.setUint32(this.offset,t,this.littleEndian),this.offset+=4,this._updateLastWrittenByte(),this}writeFloat32(t){return this.ensureAvailable(4),this._data.setFloat32(this.offset,t,this.littleEndian),this.offset+=4,this._updateLastWrittenByte(),this}writeFloat64(t){return this.ensureAvailable(8),this._data.setFloat64(this.offset,t,this.littleEndian),this.offset+=8,this._updateLastWrittenByte(),this}writeChar(t){return this.writeUint8(t.charCodeAt(0))}writeChars(t){for(let e=0;e<t.length;e++)this.writeUint8(t.charCodeAt(e));return this}writeUtf8(t){return this.writeBytes(function(t){return e.encode(t)}(t))}toArray(){return new Uint8Array(this.buffer,this.byteOffset,this.lastWrittenByte)}_updateLastWrittenByte(){this.offset>this.lastWrittenByte&&(this.lastWrittenByte=this.offset)}}function a(t){let e=t.length;for(;--e>=0;)t[e]=0}const n=256,s=286,r=30,o=15,h=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),l=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),d=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),f=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),_=new Array(576);a(_);const c=new Array(60);a(c);const u=new Array(512);a(u);const w=new Array(256);a(w);const p=new Array(29);a(p);const g=new Array(r);function b(t,e,i,a,n){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=a,this.max_length=n,this.has_stree=t&&t.length}let m,k,y;function v(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}a(g);const E=t=>t<256?u[t]:u[256+(t>>>7)],A=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},x=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,A(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=i-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)},U=(t,e,i)=>{x(t,i[2*e],i[2*e+1])},z=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},R=(t,e,i)=>{const a=new Array(16);let n,s,r=0;for(n=1;n<=o;n++)a[n]=r=r+i[n-1]<<1;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=z(a[e]++,e))}},N=t=>{let e;for(e=0;e<s;e++)t.dyn_ltree[2*e]=0;for(e=0;e<r;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0},O=t=>{t.bi_valid>8?A(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},L=(t,e,i,a)=>{const n=2*e,s=2*i;return t[n]<t[s]||t[n]===t[s]&&a[e]<=a[i]},T=(t,e,i)=>{const a=t.heap[i];let n=i<<1;for(;n<=t.heap_len&&(n<t.heap_len&&L(e,t.heap[n+1],t.heap[n],t.depth)&&n++,!L(e,a,t.heap[n],t.depth));)t.heap[i]=t.heap[n],i=n,n<<=1;t.heap[i]=a},D=(t,e,i)=>{let a,s,r,o,d=0;if(0!==t.last_lit)do{a=t.pending_buf[t.d_buf+2*d]<<8|t.pending_buf[t.d_buf+2*d+1],s=t.pending_buf[t.l_buf+d],d++,0===a?U(t,s,e):(r=w[s],U(t,r+n+1,e),o=h[r],0!==o&&(s-=p[r],x(t,s,o)),a--,r=E(a),U(t,r,i),o=l[r],0!==o&&(a-=g[r],x(t,a,o)))}while(d<t.last_lit);U(t,256,e)},I=(t,e)=>{const i=e.dyn_tree,a=e.stat_desc.static_tree,n=e.stat_desc.has_stree,s=e.stat_desc.elems;let r,h,l,d=-1;for(t.heap_len=0,t.heap_max=573,r=0;r<s;r++)0!==i[2*r]?(t.heap[++t.heap_len]=d=r,t.depth[r]=0):i[2*r+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=d<2?++d:0,i[2*l]=1,t.depth[l]=0,t.opt_len--,n&&(t.static_len-=a[2*l+1]);for(e.max_code=d,r=t.heap_len>>1;r>=1;r--)T(t,i,r);l=s;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],T(t,i,1),h=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=h,i[2*l]=i[2*r]+i[2*h],t.depth[l]=(t.depth[r]>=t.depth[h]?t.depth[r]:t.depth[h])+1,i[2*r+1]=i[2*h+1]=l,t.heap[1]=l++,T(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const i=e.dyn_tree,a=e.max_code,n=e.stat_desc.static_tree,s=e.stat_desc.has_stree,r=e.stat_desc.extra_bits,h=e.stat_desc.extra_base,l=e.stat_desc.max_length;let d,f,_,c,u,w,p=0;for(c=0;c<=o;c++)t.bl_count[c]=0;for(i[2*t.heap[t.heap_max]+1]=0,d=t.heap_max+1;d<573;d++)f=t.heap[d],c=i[2*i[2*f+1]+1]+1,c>l&&(c=l,p++),i[2*f+1]=c,f>a||(t.bl_count[c]++,u=0,f>=h&&(u=r[f-h]),w=i[2*f],t.opt_len+=w*(c+u),s&&(t.static_len+=w*(n[2*f+1]+u)));if(0!==p){do{for(c=l-1;0===t.bl_count[c];)c--;t.bl_count[c]--,t.bl_count[c+1]+=2,t.bl_count[l]--,p-=2}while(p>0);for(c=l;0!==c;c--)for(f=t.bl_count[c];0!==f;)_=t.heap[--d],_>a||(i[2*_+1]!==c&&(t.opt_len+=(c-i[2*_+1])*i[2*_],i[2*_+1]=c),f--)}})(t,e),R(i,d,t.bl_count)},S=(t,e,i)=>{let a,n,s=-1,r=e[1],o=0,h=7,l=4;for(0===r&&(h=138,l=3),e[2*(i+1)+1]=65535,a=0;a<=i;a++)n=r,r=e[2*(a+1)+1],++o<h&&n===r||(o<l?t.bl_tree[2*n]+=o:0!==n?(n!==s&&t.bl_tree[2*n]++,t.bl_tree[32]++):o<=10?t.bl_tree[34]++:t.bl_tree[36]++,o=0,s=n,0===r?(h=138,l=3):n===r?(h=6,l=3):(h=7,l=4))},B=(t,e,i)=>{let a,n,s=-1,r=e[1],o=0,h=7,l=4;for(0===r&&(h=138,l=3),a=0;a<=i;a++)if(n=r,r=e[2*(a+1)+1],!(++o<h&&n===r)){if(o<l)do{U(t,n,t.bl_tree)}while(0!=--o);else 0!==n?(n!==s&&(U(t,n,t.bl_tree),o--),U(t,16,t.bl_tree),x(t,o-3,2)):o<=10?(U(t,17,t.bl_tree),x(t,o-3,3)):(U(t,18,t.bl_tree),x(t,o-11,7));o=0,s=n,0===r?(h=138,l=3):n===r?(h=6,l=3):(h=7,l=4)}};let Z=!1;const C=(t,e,i,a)=>{x(t,0+(a?1:0),3),((t,e,i,a)=>{O(t),a&&(A(t,i),A(t,~i)),t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i})(t,e,i,!0)};var F={_tr_init:t=>{Z||((()=>{let t,e,i,a,n;const f=new Array(16);for(i=0,a=0;a<28;a++)for(p[a]=i,t=0;t<1<<h[a];t++)w[i++]=a;for(w[i-1]=a,n=0,a=0;a<16;a++)for(g[a]=n,t=0;t<1<<l[a];t++)u[n++]=a;for(n>>=7;a<r;a++)for(g[a]=n<<7,t=0;t<1<<l[a]-7;t++)u[256+n++]=a;for(e=0;e<=o;e++)f[e]=0;for(t=0;t<=143;)_[2*t+1]=8,t++,f[8]++;for(;t<=255;)_[2*t+1]=9,t++,f[9]++;for(;t<=279;)_[2*t+1]=7,t++,f[7]++;for(;t<=287;)_[2*t+1]=8,t++,f[8]++;for(R(_,287,f),t=0;t<r;t++)c[2*t+1]=5,c[2*t]=z(t,5);m=new b(_,h,257,s,o),k=new b(c,l,0,r,o),y=new b(new Array(0),d,0,19,7)})(),Z=!0),t.l_desc=new v(t.dyn_ltree,m),t.d_desc=new v(t.dyn_dtree,k),t.bl_desc=new v(t.bl_tree,y),t.bi_buf=0,t.bi_valid=0,N(t)},_tr_stored_block:C,_tr_flush_block:(t,e,i,a)=>{let s,r,o=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<n;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),I(t,t.l_desc),I(t,t.d_desc),o=(t=>{let e;for(S(t,t.dyn_ltree,t.l_desc.max_code),S(t,t.dyn_dtree,t.d_desc.max_code),I(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*f[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),s=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=s&&(s=r)):s=r=i+5,i+4<=s&&-1!==e?C(t,e,i,a):4===t.strategy||r===s?(x(t,2+(a?1:0),3),D(t,_,c)):(x(t,4+(a?1:0),3),((t,e,i,a)=>{let n;for(x(t,e-257,5),x(t,i-1,5),x(t,a-4,4),n=0;n<a;n++)x(t,t.bl_tree[2*f[n]+1],3);B(t,t.dyn_ltree,e-1),B(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,o+1),D(t,t.dyn_ltree,t.dyn_dtree)),N(t),a&&O(t)},_tr_tally:(t,e,i)=>(t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&i,t.last_lit++,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(w[i]+n+1)]++,t.dyn_dtree[2*E(e)]++),t.last_lit===t.lit_bufsize-1),_tr_align:t=>{x(t,2,3),U(t,256,_),(t=>{16===t.bi_valid?(A(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var M=(t,e,i,a)=>{let n=65535&t|0,s=t>>>16&65535|0,r=0;for(;0!==i;){r=i>2e3?2e3:i,i-=r;do{n=n+e[a++]|0,s=s+n|0}while(--r);n%=65521,s%=65521}return n|s<<16|0};const H=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var a=0;a<8;a++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var P=(t,e,i,a)=>{const n=H,s=a+i;t^=-1;for(let i=a;i<s;i++)t=t>>>8^n[255&(t^e[i])];return-1^t},W={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},K={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:$,_tr_stored_block:Y,_tr_flush_block:j,_tr_tally:G,_tr_align:X}=F,{Z_NO_FLUSH:V,Z_PARTIAL_FLUSH:q,Z_FULL_FLUSH:J,Z_FINISH:Q,Z_BLOCK:tt,Z_OK:et,Z_STREAM_END:it,Z_STREAM_ERROR:at,Z_DATA_ERROR:nt,Z_BUF_ERROR:st,Z_DEFAULT_COMPRESSION:rt,Z_FILTERED:ot,Z_HUFFMAN_ONLY:ht,Z_RLE:lt,Z_FIXED:dt,Z_DEFAULT_STRATEGY:ft,Z_UNKNOWN:_t,Z_DEFLATED:ct}=K,ut=258,wt=262,pt=103,gt=113,bt=666,mt=(t,e)=>(t.msg=W[e],e),kt=t=>(t<<1)-(t>4?9:0),yt=t=>{let e=t.length;for(;--e>=0;)t[e]=0};let vt=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const Et=t=>{const e=t.state;let i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+i),t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))},At=(t,e)=>{j(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,Et(t.strm)},xt=(t,e)=>{t.pending_buf[t.pending++]=e},Ut=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},zt=(t,e,i,a)=>{let n=t.avail_in;return n>a&&(n=a),0===n?0:(t.avail_in-=n,e.set(t.input.subarray(t.next_in,t.next_in+n),i),1===t.state.wrap?t.adler=M(t.adler,e,n,i):2===t.state.wrap&&(t.adler=P(t.adler,e,n,i)),t.next_in+=n,t.total_in+=n,n)},Rt=(t,e)=>{let i,a,n=t.max_chain_length,s=t.strstart,r=t.prev_length,o=t.nice_match;const h=t.strstart>t.w_size-wt?t.strstart-(t.w_size-wt):0,l=t.window,d=t.w_mask,f=t.prev,_=t.strstart+ut;let c=l[s+r-1],u=l[s+r];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do{if(i=e,l[i+r]===u&&l[i+r-1]===c&&l[i]===l[s]&&l[++i]===l[s+1]){s+=2,i++;do{}while(l[++s]===l[++i]&&l[++s]===l[++i]&&l[++s]===l[++i]&&l[++s]===l[++i]&&l[++s]===l[++i]&&l[++s]===l[++i]&&l[++s]===l[++i]&&l[++s]===l[++i]&&s<_);if(a=ut-(_-s),s=_-ut,a>r){if(t.match_start=e,r=a,a>=o)break;c=l[s+r-1],u=l[s+r]}}}while((e=f[e&d])>h&&0!=--n);return r<=t.lookahead?r:t.lookahead},Nt=t=>{const e=t.w_size;let i,a,n,s,r;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-wt)){t.window.set(t.window.subarray(e,e+e),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,a=t.hash_size,i=a;do{n=t.head[--i],t.head[i]=n>=e?n-e:0}while(--a);a=e,i=a;do{n=t.prev[--i],t.prev[i]=n>=e?n-e:0}while(--a);s+=e}if(0===t.strm.avail_in)break;if(a=zt(t.strm,t.window,t.strstart+t.lookahead,s),t.lookahead+=a,t.lookahead+t.insert>=3)for(r=t.strstart-t.insert,t.ins_h=t.window[r],t.ins_h=vt(t,t.ins_h,t.window[r+1]);t.insert&&(t.ins_h=vt(t,t.ins_h,t.window[r+3-1]),t.prev[r&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=r,r++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<wt&&0!==t.strm.avail_in)},Ot=(t,e)=>{let i,a;for(;;){if(t.lookahead<wt){if(Nt(t),t.lookahead<wt&&e===V)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=vt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-wt&&(t.match_length=Rt(t,i)),t.match_length>=3)if(a=G(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=vt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=vt(t,t.ins_h,t.window[t.strstart+1]);else a=G(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(a&&(At(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===Q?(At(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(At(t,!1),0===t.strm.avail_out)?1:2},Lt=(t,e)=>{let i,a,n;for(;;){if(t.lookahead<wt){if(Nt(t),t.lookahead<wt&&e===V)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=vt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-wt&&(t.match_length=Rt(t,i),t.match_length<=5&&(t.strategy===ot||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-3,a=G(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=vt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,a&&(At(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(a=G(t,0,t.window[t.strstart-1]),a&&At(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(a=G(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===Q?(At(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(At(t,!1),0===t.strm.avail_out)?1:2};function Tt(t,e,i,a,n){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=a,this.func=n}const Dt=[new Tt(0,0,0,0,((t,e)=>{let i=65535;for(i>t.pending_buf_size-5&&(i=t.pending_buf_size-5);;){if(t.lookahead<=1){if(Nt(t),0===t.lookahead&&e===V)return 1;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;const a=t.block_start+i;if((0===t.strstart||t.strstart>=a)&&(t.lookahead=t.strstart-a,t.strstart=a,At(t,!1),0===t.strm.avail_out))return 1;if(t.strstart-t.block_start>=t.w_size-wt&&(At(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Q?(At(t,!0),0===t.strm.avail_out?3:4):(t.strstart>t.block_start&&(At(t,!1),t.strm.avail_out),1)})),new Tt(4,4,8,4,Ot),new Tt(4,5,16,8,Ot),new Tt(4,6,32,32,Ot),new Tt(4,4,16,16,Lt),new Tt(8,16,32,32,Lt),new Tt(8,16,128,128,Lt),new Tt(8,32,128,256,Lt),new Tt(32,128,258,1024,Lt),new Tt(32,258,258,4096,Lt)];function It(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ct,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),yt(this.dyn_ltree),yt(this.dyn_dtree),yt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),yt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),yt(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const St=t=>{if(!t||!t.state)return mt(t,at);t.total_in=t.total_out=0,t.data_type=_t;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?42:gt,t.adler=2===e.wrap?0:1,e.last_flush=V,$(e),et},Bt=t=>{const e=St(t);var i;return e===et&&((i=t.state).window_size=2*i.w_size,yt(i.head),i.max_lazy_match=Dt[i.level].max_lazy,i.good_match=Dt[i.level].good_length,i.nice_match=Dt[i.level].nice_length,i.max_chain_length=Dt[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),e},Zt=(t,e,i,a,n,s)=>{if(!t)return at;let r=1;if(e===rt&&(e=6),a<0?(r=0,a=-a):a>15&&(r=2,a-=16),n<1||n>9||i!==ct||a<8||a>15||e<0||e>9||s<0||s>dt)return mt(t,at);8===a&&(a=9);const o=new It;return t.state=o,o.strm=t,o.wrap=r,o.gzhead=null,o.w_bits=a,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=n+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<n+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.d_buf=1*o.lit_bufsize,o.l_buf=3*o.lit_bufsize,o.level=e,o.strategy=s,o.method=i,Bt(t)};var Ct={deflateInit:(t,e)=>Zt(t,e,ct,15,8,ft),deflateInit2:Zt,deflateReset:Bt,deflateResetKeep:St,deflateSetHeader:(t,e)=>t&&t.state?2!==t.state.wrap?at:(t.state.gzhead=e,et):at,deflate:(t,e)=>{let i,a;if(!t||!t.state||e>tt||e<0)return t?mt(t,at):at;const n=t.state;if(!t.output||!t.input&&0!==t.avail_in||n.status===bt&&e!==Q)return mt(t,0===t.avail_out?st:at);n.strm=t;const s=n.last_flush;if(n.last_flush=e,42===n.status)if(2===n.wrap)t.adler=0,xt(n,31),xt(n,139),xt(n,8),n.gzhead?(xt(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),xt(n,255&n.gzhead.time),xt(n,n.gzhead.time>>8&255),xt(n,n.gzhead.time>>16&255),xt(n,n.gzhead.time>>24&255),xt(n,9===n.level?2:n.strategy>=ht||n.level<2?4:0),xt(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(xt(n,255&n.gzhead.extra.length),xt(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=P(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(xt(n,0),xt(n,0),xt(n,0),xt(n,0),xt(n,0),xt(n,9===n.level?2:n.strategy>=ht||n.level<2?4:0),xt(n,3),n.status=gt);else{let e=ct+(n.w_bits-8<<4)<<8,i=-1;i=n.strategy>=ht||n.level<2?0:n.level<6?1:6===n.level?2:3,e|=i<<6,0!==n.strstart&&(e|=32),e+=31-e%31,n.status=gt,Ut(n,e),0!==n.strstart&&(Ut(n,t.adler>>>16),Ut(n,65535&t.adler)),t.adler=1}if(69===n.status)if(n.gzhead.extra){for(i=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>i&&(t.adler=P(t.adler,n.pending_buf,n.pending-i,i)),Et(t),i=n.pending,n.pending!==n.pending_buf_size));)xt(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>i&&(t.adler=P(t.adler,n.pending_buf,n.pending-i,i)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(t.adler=P(t.adler,n.pending_buf,n.pending-i,i)),Et(t),i=n.pending,n.pending===n.pending_buf_size)){a=1;break}a=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,xt(n,a)}while(0!==a);n.gzhead.hcrc&&n.pending>i&&(t.adler=P(t.adler,n.pending_buf,n.pending-i,i)),0===a&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(t.adler=P(t.adler,n.pending_buf,n.pending-i,i)),Et(t),i=n.pending,n.pending===n.pending_buf_size)){a=1;break}a=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,xt(n,a)}while(0!==a);n.gzhead.hcrc&&n.pending>i&&(t.adler=P(t.adler,n.pending_buf,n.pending-i,i)),0===a&&(n.status=pt)}else n.status=pt;if(n.status===pt&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&Et(t),n.pending+2<=n.pending_buf_size&&(xt(n,255&t.adler),xt(n,t.adler>>8&255),t.adler=0,n.status=gt)):n.status=gt),0!==n.pending){if(Et(t),0===t.avail_out)return n.last_flush=-1,et}else if(0===t.avail_in&&kt(e)<=kt(s)&&e!==Q)return mt(t,st);if(n.status===bt&&0!==t.avail_in)return mt(t,st);if(0!==t.avail_in||0!==n.lookahead||e!==V&&n.status!==bt){let i=n.strategy===ht?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(Nt(t),0===t.lookahead)){if(e===V)return 1;break}if(t.match_length=0,i=G(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(At(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Q?(At(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(At(t,!1),0===t.strm.avail_out)?1:2})(n,e):n.strategy===lt?((t,e)=>{let i,a,n,s;const r=t.window;for(;;){if(t.lookahead<=ut){if(Nt(t),t.lookahead<=ut&&e===V)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=t.strstart-1,a=r[n],a===r[++n]&&a===r[++n]&&a===r[++n])){s=t.strstart+ut;do{}while(a===r[++n]&&a===r[++n]&&a===r[++n]&&a===r[++n]&&a===r[++n]&&a===r[++n]&&a===r[++n]&&a===r[++n]&&n<s);t.match_length=ut-(s-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=G(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=G(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(At(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Q?(At(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(At(t,!1),0===t.strm.avail_out)?1:2})(n,e):Dt[n.level].func(n,e);if(3!==i&&4!==i||(n.status=bt),1===i||3===i)return 0===t.avail_out&&(n.last_flush=-1),et;if(2===i&&(e===q?X(n):e!==tt&&(Y(n,0,0,!1),e===J&&(yt(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),Et(t),0===t.avail_out))return n.last_flush=-1,et}return e!==Q?et:n.wrap<=0?it:(2===n.wrap?(xt(n,255&t.adler),xt(n,t.adler>>8&255),xt(n,t.adler>>16&255),xt(n,t.adler>>24&255),xt(n,255&t.total_in),xt(n,t.total_in>>8&255),xt(n,t.total_in>>16&255),xt(n,t.total_in>>24&255)):(Ut(n,t.adler>>>16),Ut(n,65535&t.adler)),Et(t),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?et:it)},deflateEnd:t=>{if(!t||!t.state)return at;const e=t.state.status;return 42!==e&&69!==e&&73!==e&&91!==e&&e!==pt&&e!==gt&&e!==bt?mt(t,at):(t.state=null,e===gt?mt(t,nt):et)},deflateSetDictionary:(t,e)=>{let i=e.length;if(!t||!t.state)return at;const a=t.state,n=a.wrap;if(2===n||1===n&&42!==a.status||a.lookahead)return at;if(1===n&&(t.adler=M(t.adler,e,i,0)),a.wrap=0,i>=a.w_size){0===n&&(yt(a.head),a.strstart=0,a.block_start=0,a.insert=0);let t=new Uint8Array(a.w_size);t.set(e.subarray(i-a.w_size,i),0),e=t,i=a.w_size}const s=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=i,t.next_in=0,t.input=e,Nt(a);a.lookahead>=3;){let t=a.strstart,e=a.lookahead-2;do{a.ins_h=vt(a,a.ins_h,a.window[t+3-1]),a.prev[t&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=t,t++}while(--e);a.strstart=t,a.lookahead=2,Nt(a)}return a.strstart+=a.lookahead,a.block_start=a.strstart,a.insert=a.lookahead,a.lookahead=0,a.match_length=a.prev_length=2,a.match_available=0,t.next_in=r,t.input=o,t.avail_in=s,a.wrap=n,et},deflateInfo:"pako deflate (from Nodeca project)"};const Ft=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Mt=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const e in i)Ft(i,e)&&(t[e]=i[e])}}return t},Ht=t=>{let e=0;for(let i=0,a=t.length;i<a;i++)e+=t[i].length;const i=new Uint8Array(e);for(let e=0,a=0,n=t.length;e<n;e++){let n=t[e];i.set(n,a),a+=n.length}return i};let Pt=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Pt=!1}const Wt=new Uint8Array(256);for(let t=0;t<256;t++)Wt[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Wt[254]=Wt[254]=1;var Kt=t=>{let e,i,a,n,s,r=t.length,o=0;for(n=0;n<r;n++)i=t.charCodeAt(n),55296==(64512&i)&&n+1<r&&(a=t.charCodeAt(n+1),56320==(64512&a)&&(i=65536+(i-55296<<10)+(a-56320),n++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(o),s=0,n=0;s<o;n++)i=t.charCodeAt(n),55296==(64512&i)&&n+1<r&&(a=t.charCodeAt(n+1),56320==(64512&a)&&(i=65536+(i-55296<<10)+(a-56320),n++)),i<128?e[s++]=i:i<2048?(e[s++]=192|i>>>6,e[s++]=128|63&i):i<65536?(e[s++]=224|i>>>12,e[s++]=128|i>>>6&63,e[s++]=128|63&i):(e[s++]=240|i>>>18,e[s++]=128|i>>>12&63,e[s++]=128|i>>>6&63,e[s++]=128|63&i);return e},$t=(t,e)=>{let i,a;const n=e||t.length,s=new Array(2*n);for(a=0,i=0;i<n;){let e=t[i++];if(e<128){s[a++]=e;continue}let r=Wt[e];if(r>4)s[a++]=65533,i+=r-1;else{for(e&=2===r?31:3===r?15:7;r>1&&i<n;)e=e<<6|63&t[i++],r--;r>1?s[a++]=65533:e<65536?s[a++]=e:(e-=65536,s[a++]=55296|e>>10&1023,s[a++]=56320|1023&e)}}return((t,e)=>{if(e<65534&&t.subarray&&Pt)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let i="";for(let a=0;a<e;a++)i+=String.fromCharCode(t[a]);return i})(s,a)},Yt=(t,e)=>{(e=e||t.length)>t.length&&(e=t.length);let i=e-1;for(;i>=0&&128==(192&t[i]);)i--;return i<0||0===i?e:i+Wt[t[i]]>e?i:e};var jt=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const Gt=Object.prototype.toString,{Z_NO_FLUSH:Xt,Z_SYNC_FLUSH:Vt,Z_FULL_FLUSH:qt,Z_FINISH:Jt,Z_OK:Qt,Z_STREAM_END:te,Z_DEFAULT_COMPRESSION:ee,Z_DEFAULT_STRATEGY:ie,Z_DEFLATED:ae}=K;function ne(t){this.options=Mt({level:ee,method:ae,chunkSize:16384,windowBits:15,memLevel:8,strategy:ie},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new jt,this.strm.avail_out=0;let i=Ct.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==Qt)throw new Error(W[i]);if(e.header&&Ct.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Kt(e.dictionary):"[object ArrayBuffer]"===Gt.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=Ct.deflateSetDictionary(this.strm,t),i!==Qt)throw new Error(W[i]);this._dict_set=!0}}function se(t,e){const i=new ne(e);if(i.push(t,!0),i.err)throw i.msg||W[i.err];return i.result}ne.prototype.push=function(t,e){const i=this.strm,a=this.options.chunkSize;let n,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?Jt:Xt,"string"==typeof t?i.input=Kt(t):"[object ArrayBuffer]"===Gt.call(t)?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(a),i.next_out=0,i.avail_out=a),(s===Vt||s===qt)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(n=Ct.deflate(i,s),n===te)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),n=Ct.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===Qt;if(0!==i.avail_out){if(s>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},ne.prototype.onData=function(t){this.chunks.push(t)},ne.prototype.onEnd=function(t){t===Qt&&(this.result=Ht(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var re={Deflate:ne,deflate:se,deflateRaw:function(t,e){return(e=e||{}).raw=!0,se(t,e)},gzip:function(t,e){return(e=e||{}).gzip=!0,se(t,e)},constants:K};var oe=function(t,e){let i,a,n,s,r,o,h,l,d,f,_,c,u,w,p,g,b,m,k,y,v,E,A,x;const U=t.state;i=t.next_in,A=t.input,a=i+(t.avail_in-5),n=t.next_out,x=t.output,s=n-(e-t.avail_out),r=n+(t.avail_out-257),o=U.dmax,h=U.wsize,l=U.whave,d=U.wnext,f=U.window,_=U.hold,c=U.bits,u=U.lencode,w=U.distcode,p=(1<<U.lenbits)-1,g=(1<<U.distbits)-1;t:do{c<15&&(_+=A[i++]<<c,c+=8,_+=A[i++]<<c,c+=8),b=u[_&p];e:for(;;){if(m=b>>>24,_>>>=m,c-=m,m=b>>>16&255,0===m)x[n++]=65535&b;else{if(!(16&m)){if(0==(64&m)){b=u[(65535&b)+(_&(1<<m)-1)];continue e}if(32&m){U.mode=12;break t}t.msg="invalid literal/length code",U.mode=30;break t}k=65535&b,m&=15,m&&(c<m&&(_+=A[i++]<<c,c+=8),k+=_&(1<<m)-1,_>>>=m,c-=m),c<15&&(_+=A[i++]<<c,c+=8,_+=A[i++]<<c,c+=8),b=w[_&g];i:for(;;){if(m=b>>>24,_>>>=m,c-=m,m=b>>>16&255,!(16&m)){if(0==(64&m)){b=w[(65535&b)+(_&(1<<m)-1)];continue i}t.msg="invalid distance code",U.mode=30;break t}if(y=65535&b,m&=15,c<m&&(_+=A[i++]<<c,c+=8,c<m&&(_+=A[i++]<<c,c+=8)),y+=_&(1<<m)-1,y>o){t.msg="invalid distance too far back",U.mode=30;break t}if(_>>>=m,c-=m,m=n-s,y>m){if(m=y-m,m>l&&U.sane){t.msg="invalid distance too far back",U.mode=30;break t}if(v=0,E=f,0===d){if(v+=h-m,m<k){k-=m;do{x[n++]=f[v++]}while(--m);v=n-y,E=x}}else if(d<m){if(v+=h+d-m,m-=d,m<k){k-=m;do{x[n++]=f[v++]}while(--m);if(v=0,d<k){m=d,k-=m;do{x[n++]=f[v++]}while(--m);v=n-y,E=x}}}else if(v+=d-m,m<k){k-=m;do{x[n++]=f[v++]}while(--m);v=n-y,E=x}for(;k>2;)x[n++]=E[v++],x[n++]=E[v++],x[n++]=E[v++],k-=3;k&&(x[n++]=E[v++],k>1&&(x[n++]=E[v++]))}else{v=n-y;do{x[n++]=x[v++],x[n++]=x[v++],x[n++]=x[v++],k-=3}while(k>2);k&&(x[n++]=x[v++],k>1&&(x[n++]=x[v++]))}break}}break}}while(i<a&&n<r);k=c>>3,i-=k,c-=k<<3,_&=(1<<c)-1,t.next_in=i,t.next_out=n,t.avail_in=i<a?a-i+5:5-(i-a),t.avail_out=n<r?r-n+257:257-(n-r),U.hold=_,U.bits=c};const he=15,le=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),de=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),fe=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),_e=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var ce=(t,e,i,a,n,s,r,o)=>{const h=o.bits;let l,d,f,_,c,u,w=0,p=0,g=0,b=0,m=0,k=0,y=0,v=0,E=0,A=0,x=null,U=0;const z=new Uint16Array(16),R=new Uint16Array(16);let N,O,L,T=null,D=0;for(w=0;w<=he;w++)z[w]=0;for(p=0;p<a;p++)z[e[i+p]]++;for(m=h,b=he;b>=1&&0===z[b];b--);if(m>b&&(m=b),0===b)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(g=1;g<b&&0===z[g];g++);for(m<g&&(m=g),v=1,w=1;w<=he;w++)if(v<<=1,v-=z[w],v<0)return-1;if(v>0&&(0===t||1!==b))return-1;for(R[1]=0,w=1;w<he;w++)R[w+1]=R[w]+z[w];for(p=0;p<a;p++)0!==e[i+p]&&(r[R[e[i+p]]++]=p);if(0===t?(x=T=r,u=19):1===t?(x=le,U-=257,T=de,D-=257,u=256):(x=fe,T=_e,u=-1),A=0,p=0,w=g,c=s,k=m,y=0,f=-1,E=1<<m,_=E-1,1===t&&E>852||2===t&&E>592)return 1;for(;;){N=w-y,r[p]<u?(O=0,L=r[p]):r[p]>u?(O=T[D+r[p]],L=x[U+r[p]]):(O=96,L=0),l=1<<w-y,d=1<<k,g=d;do{d-=l,n[c+(A>>y)+d]=N<<24|O<<16|L|0}while(0!==d);for(l=1<<w-1;A&l;)l>>=1;if(0!==l?(A&=l-1,A+=l):A=0,p++,0==--z[w]){if(w===b)break;w=e[i+r[p]]}if(w>m&&(A&_)!==f){for(0===y&&(y=m),c+=g,k=w-y,v=1<<k;k+y<b&&(v-=z[k+y],!(v<=0));)k++,v<<=1;if(E+=1<<k,1===t&&E>852||2===t&&E>592)return 1;f=A&_,n[f]=m<<24|k<<16|c-s|0}}return 0!==A&&(n[c+A]=w-y<<24|64<<16|0),o.bits=m,0};const{Z_FINISH:ue,Z_BLOCK:we,Z_TREES:pe,Z_OK:ge,Z_STREAM_END:be,Z_NEED_DICT:me,Z_STREAM_ERROR:ke,Z_DATA_ERROR:ye,Z_MEM_ERROR:ve,Z_BUF_ERROR:Ee,Z_DEFLATED:Ae}=K,xe=12,Ue=30,ze=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function Re(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const Ne=t=>{if(!t||!t.state)return ke;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=1,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,ge},Oe=t=>{if(!t||!t.state)return ke;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,Ne(t)},Le=(t,e)=>{let i;if(!t||!t.state)return ke;const a=t.state;return e<0?(i=0,e=-e):(i=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?ke:(null!==a.window&&a.wbits!==e&&(a.window=null),a.wrap=i,a.wbits=e,Oe(t))},Te=(t,e)=>{if(!t)return ke;const i=new Re;t.state=i,i.window=null;const a=Le(t,e);return a!==ge&&(t.state=null),a};let De,Ie,Se=!0;const Be=t=>{if(Se){De=new Int32Array(512),Ie=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(ce(1,t.lens,0,288,De,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;ce(2,t.lens,0,32,Ie,0,t.work,{bits:5}),Se=!1}t.lencode=De,t.lenbits=9,t.distcode=Ie,t.distbits=5},Ze=(t,e,i,a)=>{let n;const s=t.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),a>=s.wsize?(s.window.set(e.subarray(i-s.wsize,i),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>a&&(n=a),s.window.set(e.subarray(i-a,i-a+n),s.wnext),(a-=n)?(s.window.set(e.subarray(i-a,i),0),s.wnext=a,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=n))),0};var Ce={inflateReset:Oe,inflateReset2:Le,inflateResetKeep:Ne,inflateInit:t=>Te(t,15),inflateInit2:Te,inflate:(t,e)=>{let i,a,n,s,r,o,h,l,d,f,_,c,u,w,p,g,b,m,k,y,v,E,A=0;const x=new Uint8Array(4);let U,z;const R=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return ke;i=t.state,i.mode===xe&&(i.mode=13),r=t.next_out,n=t.output,h=t.avail_out,s=t.next_in,a=t.input,o=t.avail_in,l=i.hold,d=i.bits,f=o,_=h,E=ge;t:for(;;)switch(i.mode){case 1:if(0===i.wrap){i.mode=13;break}for(;d<16;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}if(2&i.wrap&&35615===l){i.check=0,x[0]=255&l,x[1]=l>>>8&255,i.check=P(i.check,x,2,0),l=0,d=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&l)<<8)+(l>>8))%31){t.msg="incorrect header check",i.mode=Ue;break}if((15&l)!==Ae){t.msg="unknown compression method",i.mode=Ue;break}if(l>>>=4,d-=4,v=8+(15&l),0===i.wbits)i.wbits=v;else if(v>i.wbits){t.msg="invalid window size",i.mode=Ue;break}i.dmax=1<<i.wbits,t.adler=i.check=1,i.mode=512&l?10:xe,l=0,d=0;break;case 2:for(;d<16;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}if(i.flags=l,(255&i.flags)!==Ae){t.msg="unknown compression method",i.mode=Ue;break}if(57344&i.flags){t.msg="unknown header flags set",i.mode=Ue;break}i.head&&(i.head.text=l>>8&1),512&i.flags&&(x[0]=255&l,x[1]=l>>>8&255,i.check=P(i.check,x,2,0)),l=0,d=0,i.mode=3;case 3:for(;d<32;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}i.head&&(i.head.time=l),512&i.flags&&(x[0]=255&l,x[1]=l>>>8&255,x[2]=l>>>16&255,x[3]=l>>>24&255,i.check=P(i.check,x,4,0)),l=0,d=0,i.mode=4;case 4:for(;d<16;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}i.head&&(i.head.xflags=255&l,i.head.os=l>>8),512&i.flags&&(x[0]=255&l,x[1]=l>>>8&255,i.check=P(i.check,x,2,0)),l=0,d=0,i.mode=5;case 5:if(1024&i.flags){for(;d<16;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}i.length=l,i.head&&(i.head.extra_len=l),512&i.flags&&(x[0]=255&l,x[1]=l>>>8&255,i.check=P(i.check,x,2,0)),l=0,d=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(c=i.length,c>o&&(c=o),c&&(i.head&&(v=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(a.subarray(s,s+c),v)),512&i.flags&&(i.check=P(i.check,a,c,s)),o-=c,s+=c,i.length-=c),i.length))break t;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===o)break t;c=0;do{v=a[s+c++],i.head&&v&&i.length<65536&&(i.head.name+=String.fromCharCode(v))}while(v&&c<o);if(512&i.flags&&(i.check=P(i.check,a,c,s)),o-=c,s+=c,v)break t}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===o)break t;c=0;do{v=a[s+c++],i.head&&v&&i.length<65536&&(i.head.comment+=String.fromCharCode(v))}while(v&&c<o);if(512&i.flags&&(i.check=P(i.check,a,c,s)),o-=c,s+=c,v)break t}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;d<16;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}if(l!==(65535&i.check)){t.msg="header crc mismatch",i.mode=Ue;break}l=0,d=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),t.adler=i.check=0,i.mode=xe;break;case 10:for(;d<32;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}t.adler=i.check=ze(l),l=0,d=0,i.mode=11;case 11:if(0===i.havedict)return t.next_out=r,t.avail_out=h,t.next_in=s,t.avail_in=o,i.hold=l,i.bits=d,me;t.adler=i.check=1,i.mode=xe;case xe:if(e===we||e===pe)break t;case 13:if(i.last){l>>>=7&d,d-=7&d,i.mode=27;break}for(;d<3;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}switch(i.last=1&l,l>>>=1,d-=1,3&l){case 0:i.mode=14;break;case 1:if(Be(i),i.mode=20,e===pe){l>>>=2,d-=2;break t}break;case 2:i.mode=17;break;case 3:t.msg="invalid block type",i.mode=Ue}l>>>=2,d-=2;break;case 14:for(l>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}if((65535&l)!=(l>>>16^65535)){t.msg="invalid stored block lengths",i.mode=Ue;break}if(i.length=65535&l,l=0,d=0,i.mode=15,e===pe)break t;case 15:i.mode=16;case 16:if(c=i.length,c){if(c>o&&(c=o),c>h&&(c=h),0===c)break t;n.set(a.subarray(s,s+c),r),o-=c,s+=c,h-=c,r+=c,i.length-=c;break}i.mode=xe;break;case 17:for(;d<14;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}if(i.nlen=257+(31&l),l>>>=5,d-=5,i.ndist=1+(31&l),l>>>=5,d-=5,i.ncode=4+(15&l),l>>>=4,d-=4,i.nlen>286||i.ndist>30){t.msg="too many length or distance symbols",i.mode=Ue;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;d<3;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}i.lens[R[i.have++]]=7&l,l>>>=3,d-=3}for(;i.have<19;)i.lens[R[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,U={bits:i.lenbits},E=ce(0,i.lens,0,19,i.lencode,0,i.work,U),i.lenbits=U.bits,E){t.msg="invalid code lengths set",i.mode=Ue;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;A=i.lencode[l&(1<<i.lenbits)-1],p=A>>>24,g=A>>>16&255,b=65535&A,!(p<=d);){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}if(b<16)l>>>=p,d-=p,i.lens[i.have++]=b;else{if(16===b){for(z=p+2;d<z;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}if(l>>>=p,d-=p,0===i.have){t.msg="invalid bit length repeat",i.mode=Ue;break}v=i.lens[i.have-1],c=3+(3&l),l>>>=2,d-=2}else if(17===b){for(z=p+3;d<z;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}l>>>=p,d-=p,v=0,c=3+(7&l),l>>>=3,d-=3}else{for(z=p+7;d<z;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}l>>>=p,d-=p,v=0,c=11+(127&l),l>>>=7,d-=7}if(i.have+c>i.nlen+i.ndist){t.msg="invalid bit length repeat",i.mode=Ue;break}for(;c--;)i.lens[i.have++]=v}}if(i.mode===Ue)break;if(0===i.lens[256]){t.msg="invalid code -- missing end-of-block",i.mode=Ue;break}if(i.lenbits=9,U={bits:i.lenbits},E=ce(1,i.lens,0,i.nlen,i.lencode,0,i.work,U),i.lenbits=U.bits,E){t.msg="invalid literal/lengths set",i.mode=Ue;break}if(i.distbits=6,i.distcode=i.distdyn,U={bits:i.distbits},E=ce(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,U),i.distbits=U.bits,E){t.msg="invalid distances set",i.mode=Ue;break}if(i.mode=20,e===pe)break t;case 20:i.mode=21;case 21:if(o>=6&&h>=258){t.next_out=r,t.avail_out=h,t.next_in=s,t.avail_in=o,i.hold=l,i.bits=d,oe(t,_),r=t.next_out,n=t.output,h=t.avail_out,s=t.next_in,a=t.input,o=t.avail_in,l=i.hold,d=i.bits,i.mode===xe&&(i.back=-1);break}for(i.back=0;A=i.lencode[l&(1<<i.lenbits)-1],p=A>>>24,g=A>>>16&255,b=65535&A,!(p<=d);){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}if(g&&0==(240&g)){for(m=p,k=g,y=b;A=i.lencode[y+((l&(1<<m+k)-1)>>m)],p=A>>>24,g=A>>>16&255,b=65535&A,!(m+p<=d);){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}l>>>=m,d-=m,i.back+=m}if(l>>>=p,d-=p,i.back+=p,i.length=b,0===g){i.mode=26;break}if(32&g){i.back=-1,i.mode=xe;break}if(64&g){t.msg="invalid literal/length code",i.mode=Ue;break}i.extra=15&g,i.mode=22;case 22:if(i.extra){for(z=i.extra;d<z;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}i.length+=l&(1<<i.extra)-1,l>>>=i.extra,d-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;A=i.distcode[l&(1<<i.distbits)-1],p=A>>>24,g=A>>>16&255,b=65535&A,!(p<=d);){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}if(0==(240&g)){for(m=p,k=g,y=b;A=i.distcode[y+((l&(1<<m+k)-1)>>m)],p=A>>>24,g=A>>>16&255,b=65535&A,!(m+p<=d);){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}l>>>=m,d-=m,i.back+=m}if(l>>>=p,d-=p,i.back+=p,64&g){t.msg="invalid distance code",i.mode=Ue;break}i.offset=b,i.extra=15&g,i.mode=24;case 24:if(i.extra){for(z=i.extra;d<z;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}i.offset+=l&(1<<i.extra)-1,l>>>=i.extra,d-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){t.msg="invalid distance too far back",i.mode=Ue;break}i.mode=25;case 25:if(0===h)break t;if(c=_-h,i.offset>c){if(c=i.offset-c,c>i.whave&&i.sane){t.msg="invalid distance too far back",i.mode=Ue;break}c>i.wnext?(c-=i.wnext,u=i.wsize-c):u=i.wnext-c,c>i.length&&(c=i.length),w=i.window}else w=n,u=r-i.offset,c=i.length;c>h&&(c=h),h-=c,i.length-=c;do{n[r++]=w[u++]}while(--c);0===i.length&&(i.mode=21);break;case 26:if(0===h)break t;n[r++]=i.length,h--,i.mode=21;break;case 27:if(i.wrap){for(;d<32;){if(0===o)break t;o--,l|=a[s++]<<d,d+=8}if(_-=h,t.total_out+=_,i.total+=_,_&&(t.adler=i.check=i.flags?P(i.check,n,_,r-_):M(i.check,n,_,r-_)),_=h,(i.flags?l:ze(l))!==i.check){t.msg="incorrect data check",i.mode=Ue;break}l=0,d=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;d<32;){if(0===o)break t;o--,l+=a[s++]<<d,d+=8}if(l!==(4294967295&i.total)){t.msg="incorrect length check",i.mode=Ue;break}l=0,d=0}i.mode=29;case 29:E=be;break t;case Ue:E=ye;break t;case 31:return ve;case 32:default:return ke}return t.next_out=r,t.avail_out=h,t.next_in=s,t.avail_in=o,i.hold=l,i.bits=d,(i.wsize||_!==t.avail_out&&i.mode<Ue&&(i.mode<27||e!==ue))&&Ze(t,t.output,t.next_out,_-t.avail_out),f-=t.avail_in,_-=t.avail_out,t.total_in+=f,t.total_out+=_,i.total+=_,i.wrap&&_&&(t.adler=i.check=i.flags?P(i.check,n,_,t.next_out-_):M(i.check,n,_,t.next_out-_)),t.data_type=i.bits+(i.last?64:0)+(i.mode===xe?128:0)+(20===i.mode||15===i.mode?256:0),(0===f&&0===_||e===ue)&&E===ge&&(E=Ee),E},inflateEnd:t=>{if(!t||!t.state)return ke;let e=t.state;return e.window&&(e.window=null),t.state=null,ge},inflateGetHeader:(t,e)=>{if(!t||!t.state)return ke;const i=t.state;return 0==(2&i.wrap)?ke:(i.head=e,e.done=!1,ge)},inflateSetDictionary:(t,e)=>{const i=e.length;let a,n,s;return t&&t.state?(a=t.state,0!==a.wrap&&11!==a.mode?ke:11===a.mode&&(n=1,n=M(n,e,i,0),n!==a.check)?ye:(s=Ze(t,e,i,i),s?(a.mode=31,ve):(a.havedict=1,ge))):ke},inflateInfo:"pako inflate (from Nodeca project)"};var Fe=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const Me=Object.prototype.toString,{Z_NO_FLUSH:He,Z_FINISH:Pe,Z_OK:We,Z_STREAM_END:Ke,Z_NEED_DICT:$e,Z_STREAM_ERROR:Ye,Z_DATA_ERROR:je,Z_MEM_ERROR:Ge}=K;function Xe(t){this.options=Mt({chunkSize:65536,windowBits:15,to:""},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new jt,this.strm.avail_out=0;let i=Ce.inflateInit2(this.strm,e.windowBits);if(i!==We)throw new Error(W[i]);if(this.header=new Fe,Ce.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=Kt(e.dictionary):"[object ArrayBuffer]"===Me.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(i=Ce.inflateSetDictionary(this.strm,e.dictionary),i!==We)))throw new Error(W[i])}function Ve(t,e){const i=new Xe(e);if(i.push(t),i.err)throw i.msg||W[i.err];return i.result}Xe.prototype.push=function(t,e){const i=this.strm,a=this.options.chunkSize,n=this.options.dictionary;let s,r,o;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Pe:He,"[object ArrayBuffer]"===Me.call(t)?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(a),i.next_out=0,i.avail_out=a),s=Ce.inflate(i,r),s===$e&&n&&(s=Ce.inflateSetDictionary(i,n),s===We?s=Ce.inflate(i,r):s===je&&(s=$e));i.avail_in>0&&s===Ke&&i.state.wrap>0&&0!==t[i.next_in];)Ce.inflateReset(i),s=Ce.inflate(i,r);switch(s){case Ye:case je:case $e:case Ge:return this.onEnd(s),this.ended=!0,!1}if(o=i.avail_out,i.next_out&&(0===i.avail_out||s===Ke))if("string"===this.options.to){let t=Yt(i.output,i.next_out),e=i.next_out-t,n=$t(i.output,t);i.next_out=e,i.avail_out=a-e,e&&i.output.set(i.output.subarray(t,t+e),0),this.onData(n)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(s!==We||0!==o){if(s===Ke)return s=Ce.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},Xe.prototype.onData=function(t){this.chunks.push(t)},Xe.prototype.onEnd=function(t){t===We&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=Ht(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var qe={Inflate:Xe,inflate:Ve,inflateRaw:function(t,e){return(e=e||{}).raw=!0,Ve(t,e)},ungzip:Ve,constants:K};const{Deflate:Je,deflate:Qe,deflateRaw:ti,gzip:ei}=re,{Inflate:ii,inflate:ai,inflateRaw:ni,ungzip:si}=qe;var ri=ii;const oi=[137,80,78,71,13,10,26,10],hi=[];for(let t=0;t<256;t++){let e=t;for(let t=0;t<8;t++)1&e?e=3988292384^e>>>1:e>>>=1;hi[t]=e}const li=4294967295;function di(t,e){return(function(t,e,i){let a=t;for(let t=0;t<i;t++)a=hi[255&(a^e[t])]^a>>>8;return a}(li,t,e)^li)>>>0}var fi,_i,ci,ui;!function(t){t[t.UNKNOWN=-1]="UNKNOWN",t[t.GREYSCALE=0]="GREYSCALE",t[t.TRUECOLOUR=2]="TRUECOLOUR",t[t.INDEXED_COLOUR=3]="INDEXED_COLOUR",t[t.GREYSCALE_ALPHA=4]="GREYSCALE_ALPHA",t[t.TRUECOLOUR_ALPHA=6]="TRUECOLOUR_ALPHA"}(fi||(fi={})),function(t){t[t.UNKNOWN=-1]="UNKNOWN",t[t.DEFLATE=0]="DEFLATE"}(_i||(_i={})),function(t){t[t.UNKNOWN=-1]="UNKNOWN",t[t.ADAPTIVE=0]="ADAPTIVE"}(ci||(ci={})),function(t){t[t.UNKNOWN=-1]="UNKNOWN",t[t.NO_INTERLACE=0]="NO_INTERLACE",t[t.ADAM7=1]="ADAM7"}(ui||(ui={}));const wi=new Uint8Array(0),pi=new Uint16Array([255]),gi=255===new Uint8Array(pi.buffer)[0];class PNGDecoder extends IOBuffer_IOBuffer{constructor(t,e={}){super(t);const{checkCrc:i=!1}=e;this._checkCrc=i,this._inflator=new ri,this._png={width:-1,height:-1,channels:-1,data:new Uint8Array(0),depth:1,text:{}},this._end=!1,this._hasPalette=!1,this._palette=[],this._compressionMethod=_i.UNKNOWN,this._filterMethod=ci.UNKNOWN,this._interlaceMethod=ui.UNKNOWN,this._colorType=-1,this.setBigEndian()}decode(){for(this.decodeSignature();!this._end;)this.decodeChunk();return this.decodeImage(),this._png}decodeSignature(){for(let t=0;t<oi.length;t++)if(this.readUint8()!==oi[t])throw new Error(`wrong PNG signature. Byte at ${t} should be ${oi[t]}.`)}decodeChunk(){const t=this.readUint32(),e=this.readChars(4),i=this.offset;switch(e){case"IHDR":this.decodeIHDR();break;case"PLTE":this.decodePLTE(t);break;case"IDAT":this.decodeIDAT(t);break;case"IEND":this._end=!0;break;case"tRNS":this.decodetRNS(t);break;case"tEXt":this.decodetEXt(t);break;case"pHYs":this.decodepHYs();break;default:this.skip(t)}if(this.offset-i!==t)throw new Error(`Length mismatch while decoding chunk ${e}`);if(this._checkCrc){const i=this.readUint32(),a=t+4,n=di(new Uint8Array(this.buffer,this.byteOffset+this.offset-a-4,a),a);if(n!==i)throw new Error(`CRC mismatch for chunk ${e}. Expected ${i}, found ${n}`)}else this.skip(4)}decodeIHDR(){const t=this._png;t.width=this.readUint32(),t.height=this.readUint32(),t.depth=function(t){if(1!==t&&2!==t&&4!==t&&8!==t&&16!==t)throw new Error(`invalid bit depth: ${t}`);return t}(this.readUint8());const e=this.readUint8();let i;switch(this._colorType=e,e){case fi.GREYSCALE:i=1;break;case fi.TRUECOLOUR:i=3;break;case fi.INDEXED_COLOUR:i=1;break;case fi.GREYSCALE_ALPHA:i=2;break;case fi.TRUECOLOUR_ALPHA:i=4;break;default:throw new Error(`Unknown color type: ${e}`)}if(this._png.channels=i,this._compressionMethod=this.readUint8(),this._compressionMethod!==_i.DEFLATE)throw new Error(`Unsupported compression method: ${this._compressionMethod}`);this._filterMethod=this.readUint8(),this._interlaceMethod=this.readUint8()}decodePLTE(t){if(t%3!=0)throw new RangeError(`PLTE field length must be a multiple of 3. Got ${t}`);const e=t/3;this._hasPalette=!0;const i=[];this._palette=i;for(let t=0;t<e;t++)i.push([this.readUint8(),this.readUint8(),this.readUint8()])}decodeIDAT(t){this._inflator.push(new Uint8Array(this.buffer,this.offset+this.byteOffset,t)),this.skip(t)}decodetRNS(t){if(3===this._colorType){if(t>this._palette.length)throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${t} vs ${this._palette.length})`);let e=0;for(;e<t;e++){const t=this.readByte();this._palette[e].push(t)}for(;e<this._palette.length;e++)this._palette[e].push(255)}}decodetEXt(t){let e,i="";for(;"\\0"!==(e=this.readChar());)i+=e;this._png.text[i]=this.readChars(t-i.length-1)}decodepHYs(){const t=this.readUint32(),e=this.readUint32(),i=this.readByte();this._png.resolution={x:t,y:e,unit:i}}decodeImage(){if(this._inflator.err)throw new Error(`Error while decompressing the data: ${this._inflator.err}`);const t=this._inflator.result;if(this._filterMethod!==ci.ADAPTIVE)throw new Error(`Filter method ${this._filterMethod} not supported`);if(this._interlaceMethod!==ui.NO_INTERLACE)throw new Error(`Interlace method ${this._interlaceMethod} not supported`);this.decodeInterlaceNull(t)}decodeInterlaceNull(t){const e=this._png.height,i=this._png.channels*this._png.depth/8,a=this._png.width*i,n=new Uint8Array(this._png.height*a);let s,r,o=wi,h=0;for(let l=0;l<e;l++){switch(s=t.subarray(h+1,h+1+a),r=n.subarray(l*a,(l+1)*a),t[h]){case 0:bi(s,r,a);break;case 1:mi(s,r,a,i);break;case 2:ki(s,r,o,a);break;case 3:yi(s,r,o,a,i);break;case 4:vi(s,r,o,a,i);break;default:throw new Error(`Unsupported filter: ${t[h]}`)}o=r,h+=a+1}if(this._hasPalette&&(this._png.palette=this._palette),16===this._png.depth){const t=new Uint16Array(n.buffer);if(gi)for(let e=0;e<t.length;e++)t[e]=(255&(l=t[e]))<<8|l>>8&255;this._png.data=t}else this._png.data=n;var l}}function bi(t,e,i){for(let a=0;a<i;a++)e[a]=t[a]}function mi(t,e,i,a){let n=0;for(;n<a;n++)e[n]=t[n];for(;n<i;n++)e[n]=t[n]+e[n-a]&255}function ki(t,e,i,a){let n=0;if(0===i.length)for(;n<a;n++)e[n]=t[n];else for(;n<a;n++)e[n]=t[n]+i[n]&255}function yi(t,e,i,a,n){let s=0;if(0===i.length){for(;s<n;s++)e[s]=t[s];for(;s<a;s++)e[s]=t[s]+(e[s-n]>>1)&255}else{for(;s<n;s++)e[s]=t[s]+(i[s]>>1)&255;for(;s<a;s++)e[s]=t[s]+(e[s-n]+i[s]>>1)&255}}function vi(t,e,i,a,n){let s=0;if(0===i.length){for(;s<n;s++)e[s]=t[s];for(;s<a;s++)e[s]=t[s]+e[s-n]&255}else{for(;s<n;s++)e[s]=t[s]+i[s]&255;for(;s<a;s++)e[s]=t[s]+Ei(e[s-n],i[s],i[s-n])&255}}function Ei(t,e,i){const a=t+e-i,n=Math.abs(a-t),s=Math.abs(a-e),r=Math.abs(a-i);return n<=s&&n<=r?t:s<=r?e:i}var Ai;!function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.METRE=1]="METRE"}(Ai||(Ai={})),self.addEventListener("message",(t=>{const e=t.data,i=new PNGDecoder(e,a).decode();var a;const n=i.data.buffer;postMessage({data:n,width:i.width,height:i.height},[n])}))})()})();',
    "Worker",
    void 0,
    void 0
  )
})
let et = null
function it(t) {
  return function () {
    return (function (t) {
      return et || (et = new ImageLoader(t, tt)), et
    })(t)
  }
}
const nt = new Logger("LoaderComponent")
var st = { Error: "Error", Idle: "Idle", Loaded: "Loaded", Loading: "Loading" }

const rt = t => new LoaderComponent(new t()),
  at = (t, e) => {
    if (t && (e(t), t.children && t.children.length > 0)) for (const i of t.children) at(i, e)
  },
  ot = t => {
    at(t, t => {
      if ("Mesh" === t.type) {
        const e = t
        if ((e.geometry && e.geometry.dispose(), e.material))
          if (Array.isArray(e.material)) {
            const t = e.material
            for (const e of t) e.dispose()
          } else {
            e.material.dispose()
          }
      }
    })
  }
class LoaderComponent {
  assetLoader: any
  visibleCache: boolean
  urlCache: string
  materialUrlCache: string
  pivot: any
  inputs: {
    url: string
    materialUrl: string
    visible: boolean
    onLoaded: (t: any) => void
    localScale: { x: number; y: number; z: number }
    localRotation: { x: number; y: number; z: number }
    localPosition: { x: number; y: number; z: number }
    colliderEnabled: boolean
  }
  events: { [x: number]: boolean }
  outputs: any
  constructor(t) {
    ;(this.assetLoader = t),
      (this.visibleCache = !0),
      (this.urlCache = ""),
      (this.materialUrlCache = ""),
      (this.pivot = null),
      (this.inputs = {
        url: "",
        materialUrl: "",
        visible: !0,
        onLoaded: t => {},
        localScale: { x: 1, y: 1, z: 1 },
        localRotation: { x: 0, y: 0, z: 0 },
        localPosition: { x: 0, y: 0, z: 0 },
        colliderEnabled: !0
      }),
      (this.events = { [n.CLICK]: !0, [n.HOVER]: !0, [n.DRAG]: !1 }),
      (this.outputs = { loadingState: st.Idle })
  }
  onInit() {
    this.checkForUpdates()
  }
  onInputsUpdated() {
    this.checkForUpdates()
  }
  onEvent(t, e) {
    this.notify(t, e)
  }
  notify: any
  onDestroy() {
    this.pivot && (ot(this.pivot), (this.outputs.objectRoot = null), (this.pivot = null))
  }
  async checkForUpdates() {
    if (this.inputs.url !== this.urlCache || this.inputs.materialUrl !== this.materialUrlCache) {
      if (((this.urlCache = this.inputs.url), (this.materialUrlCache = this.inputs.materialUrl), null === this.inputs.url))
        return void (this.outputs.loadingState = st.Idle)
      const t = this.pivot
      ;(this.pivot = new THREE.Object3D()),
        (this.outputs.objectRoot = null),
        (this.outputs.collider = null),
        t && ot(t),
        nt.debug(`Loading ${this.inputs.url}`),
        (this.outputs.loadingState = st.Loading)
      const e = this.inputs.url
      let i,
        n = !1
      try {
        i = await this.assetLoader.load(this.inputs.url, this.inputs.materialUrl)
      } catch (t) {
        n = !0
      }
      if (e !== this.inputs.url) return void nt.debug(`Ignoring url ${e} since the input url changed during loading.`)
      if (n || !i) return void (this.outputs.loadingState = st.Error)
      this.pivot.add(i.objectRoot), (this.outputs.objectRoot = this.pivot)
    }
    if (
      (this.inputs.visible !== this.visibleCache &&
        this.outputs.objectRoot &&
        ((this.visibleCache = this.inputs.visible), (this.outputs.objectRoot.visible = this.visibleCache)),
      this.outputs.objectRoot && (this.outputs.collider = this.inputs.colliderEnabled ? this.pivot : null),
      this.outputs.objectRoot && this.pivot)
    ) {
      const t = this.pivot.children[0],
        e = new THREE.Euler(
          (this.inputs.localRotation.x * Math.PI) / 180,
          (this.inputs.localRotation.y * Math.PI) / 180,
          (this.inputs.localRotation.z * Math.PI) / 180,
          "YXZ"
        )
      this.pivot.quaternion.setFromEuler(e),
        t.scale.set(this.inputs.localScale.x, this.inputs.localScale.y, this.inputs.localScale.z),
        t.position.set(this.inputs.localPosition.x, this.inputs.localPosition.y, this.inputs.localPosition.z)
    }
    ;(this.outputs.loadingState = st.Loaded), this.inputs.onLoaded(this.outputs.objectRoot || null)
  }
}
var lt = {
  ONACCESSGRANTED: "ONACCESSGRANTED",
  ONACCESSREVOKED: "ONACCESSREVOKED"
}

const ht = t => {
  class CameraComponent {
    sub: any
    controller: any
    tmpPosition: THREE.Vector3
    tmpQuaternion: THREE.Quaternion
    inputs: { enabled: boolean; camera: any }
    constructor() {
      ;(this.sub = null),
        (this.controller = null),
        (this.tmpPosition = new THREE.Vector3()),
        (this.tmpQuaternion = new THREE.Quaternion()),
        (this.inputs = { enabled: !1, camera: null })
    }
    onInit() {
      this.inputs.enabled && this.requestControl()
    }
    onInputsUpdated(t) {
      t.enabled && this.release(), this.inputs.enabled && this.requestControl()
    }
    onTick() {
      const t = this.inputs.camera
      t &&
        this.controller &&
        (t.getWorldPosition(this.tmpPosition),
        t.getWorldQuaternion(this.tmpQuaternion),
        this.controller.updateCameraPosition(this.tmpPosition),
        this.controller.updateCameraRotation(this.tmpQuaternion))
    }
    onDestroy() {
      this.release()
    }
    release() {
      this.sub && (this.sub.cancel(), (this.sub = null))
    }
    requestControl() {
      this.sub = t.newSession(
        new (class Requester {
          component: any
          constructor(t) {
            this.component = t
          }
          onAccessGranted(t) {
            ;(this.component.controller = t), this.notify(t, lt.ONACCESSGRANTED)
          }
          onAccessRevoked(t) {
            ;(this.component.controller = null), this.notify(t, lt.ONACCESSREVOKED)
          }
          notify(e, i) {
            const n = this.component,
              s = { pose: t.pose, controller: e }
            n.notify(i, s)
          }
        })(this)
      )
    }
  }
  return () => new CameraComponent()
}
const wt = (t, e) => {
  class InputComponent {
    subs: any[]
    inputs: { eventsEnabled: boolean; userNavigationEnabled: boolean; unfiltered: boolean }
    constructor() {
      ;(this.subs = []),
        (this.inputs = {
          eventsEnabled: !0,
          userNavigationEnabled: !0,
          unfiltered: !0
        }),
        (this.isUserNavigationEnabled = this.isUserNavigationEnabled.bind(this))
    }
    subHandler(e, i) {
      this.inputs.unfiltered
        ? this.subs.push(t.registerUnfilteredHandler(e, t => this.notify(i, t)))
        : this.subs.push(t.registerHandler(e, t => this.notify(i, t)))
    }
    notify: any
    isUserNavigationEnabled() {
      return this.inputs.userNavigationEnabled
    }
    onInit() {
      e.addNavigationRule(this.isUserNavigationEnabled), this.inputs.eventsEnabled && this.subscribeAll()
    }
    onInputsUpdated(t) {
      t.eventsEnabled !== this.inputs.eventsEnabled
        ? this.inputs.eventsEnabled
          ? this.subscribeAll()
          : this.cancelAll()
        : t.unfiltered !== this.inputs.unfiltered && this.inputs.eventsEnabled && (this.cancelAll(), this.subscribeAll())
    }
    onDestroyed() {
      e.removeNavigationRule(this.isUserNavigationEnabled), this.cancelAll()
    }
    subscribeAll() {
      this.subs.length > 0
        ? this.subs.forEach(t => t.renew())
        : (this.subHandler(PointerMoveEvent, n.POINTER_MOVE),
          this.subHandler(DragBeginEvent, n.DRAG_BEGIN),
          this.subHandler(DragEvent, n.DRAG),
          this.subHandler(DragEndEvent, n.DRAG_END),
          this.subHandler(ScrollEvent, n.SCROLL),
          this.subHandler(PointerButtonEvent, n.POINTER_BUTTON),
          this.subHandler(KeyEvent, n.KEY),
          this.subHandler(ClickEvent, n.CLICK),
          this.subHandler(LongPressStartEvent, n.LONG_PRESS_START),
          this.subHandler(LongPressEndEvent, n.LONG_PRESS_END),
          this.subHandler(MultiSwipeEvent, n.MULTI_SWIPE),
          this.subHandler(MultiSwipeEndEvent, n.MULTI_SWIPE_END),
          this.subHandler(PinchEvent, n.PINCH),
          this.subHandler(PinchEndEvent, n.PINCH_END),
          this.subHandler(RotateEvent, n.ROTATE),
          this.subHandler(RotateEndEvent, n.ROTATE_END))
    }
    cancelAll() {
      this.subs.forEach(t => t.cancel())
    }
  }
  return () => new InputComponent()
}

const bt = t => {
  class XrComponent {
    outputs: { session: any }
    constructor() {
      this.outputs = { session: null }
    }
    onTick() {
      this.outputs.session = t.xr.getSession()
    }
  }
  return () => new XrComponent()
}
function yt(t) {
  if (null == t || isNaN(t)) return !1
  if ("number" == typeof t) return !0
  const e = parseFloat(t)
  return !isNaN(e) && "number" == typeof e
}
class PropertyBinder {
  target: any
  targetProp: any
  src: any
  srcProp: any
  initialTargetValue: any
  subscription: any
  constructor() {
    ;(this.target = null), (this.targetProp = null), (this.src = null), (this.srcProp = null)
  }
  bind(t, e, i, n) {
    ;(this.target = t),
      (this.targetProp = e),
      (this.src = i),
      (this.srcProp = n),
      (this.initialTargetValue = this.target[this.targetProp]),
      (this.target[this.targetProp] = this.src[this.srcProp]),
      (this.subscription = this.src.onPropertyChanged(this.srcProp, t => {
        this.target && this.targetProp && (this.target[this.targetProp] = t)
      }))
  }
  unbind() {
    this.target && this.targetProp && ((this.target[this.targetProp] = this.initialTargetValue), (this.target = null), (this.targetProp = null)),
      this.src && this.srcProp && (this.subscription && this.subscription.cancel(), (this.src = null), (this.srcProp = null))
  }
}
class DictionaryBinder {
  target: any
  bindings: {}
  constructor(t) {
    ;(this.target = t), (this.bindings = {})
  }
  bind(t, e, i) {
    if (this.bindings[t]) throw Error(`Property ${t} already bound.`)
    const n = new PropertyBinder()
    n.bind(this.target, t, e, i), (this.bindings[t] = n)
  }
  unbind(t) {
    const e = this.bindings[t]
    e && (e.unbind(), delete this.bindings[t])
  }
}
const vt = new Logger("SceneObject")
var Et = {
  0: "Idle",
  1: "Operating",
  2: "Stopped",
  Idle: 0,
  Operating: 1,
  Stopped: 2
}

class SceneObject {
  nodeFactory: any
  eventBus: any
  state: any
  nodes: any[]
  paths: Map<any, any>
  bindingMap: Map<any, any>
  dictionaryBinders: Map<any, any>
  idTracker: IdTracker
  constructor(t, e) {
    ;(this.nodeFactory = t),
      (this.eventBus = e),
      (this.state = Et.Idle),
      (this.nodes = []),
      (this.paths = new Map()),
      (this.bindingMap = new Map()),
      (this.dictionaryBinders = new Map()),
      (this.idTracker = new IdTracker())
  }
  addNode(t) {
    if (this.state !== Et.Idle) return vt.warn("Cannot add node after the scene object has started"), null
    const e = this.nodeFactory.createNode(this)
    if ((this.nodes.push(e), t)) {
      if (!this.idTracker.isAvailable(t)) throw Error("Component with duplicate id detected.")
      if (-1 !== t.indexOf("/")) throw Error('Node ids cannot have "/" character.')
      this.idTracker.reserve(t)
    }
    const i = t || this.idTracker.nextId()
    return (
      Object.defineProperty(e, "id", {
        value: i,
        writable: !1,
        enumerable: !0
      }),
      e
    )
  }
  *nodeIterator() {
    for (const t of this.nodes) yield t
  }
  *bindings() {
    for (const t of this.bindingMap) yield t
  }
  *pathIterator() {
    for (const [, t] of this.paths) {
      let e = null
      _(t) ? (e = new OutputPath(t)) : m(t) ? (e = new InputPath(t)) : g(t) ? (e = new EmitPath(t)) : w(t) && (e = new EventPath(t)),
        null !== e && (yield { desc: t, path: e })
    }
  }
  start() {
    if (this.state === Et.Idle) {
      for (const t of this.nodes) t.start()
      this.state = Et.Operating
    } else vt.warn("A scene object cannot be restarted.")
  }
  stop() {
    if (this.state === Et.Operating) {
      for (const t of this.nodes) t.stop()
      this.state = Et.Stopped
    }
  }
  bindPath(t, e) {
    if (m(t) && _(e)) {
      const i = this.dictionaryBinders.get(t.component) || new DictionaryBinder(t.component.inputs || {})
      return this.dictionaryBinders.set(t.component, i), i.bind(t.property, e.component.outputs, e.property), void this.bindingMap.set(t, e)
    }
    if (w(t) && g(e))
      return (
        this.bindingMap.set(t, e),
        void (function (t, e, i) {
          const n = e.component,
            s = e.property,
            r = i.component,
            a = i.property
          t.observe({
            src: r,
            srcEventType: a,
            targetEventType: s,
            onEvent(t, e) {
              n.events[t] && n.onEvent && n.onEvent(t, e)
            }
          })
        })(this.eventBus, t, e)
      )
    throw Error('Couldn\'t bind. Only an "output" can be bound to an "input", or an "emit" to an "event"')
  }
  bind(t, e, i, n) {
    if (this.state !== Et.Idle) throw Error("bind cannot be called after starting the scene node.")
    if (!t || !i) throw Error("Some bind parameters were undefined.")
    const s = this.addPath({
        id: "input-" + this.idTracker.nextId(),
        type: f.INPUT,
        node: t.context.root,
        component: t,
        property: e
      }),
      r = this.addPath({
        id: "output-" + this.idTracker.nextId(),
        type: f.OUTPUT,
        node: i.context.root,
        component: i,
        property: n
      })
    this.bindPath(s, r)
  }
  findNodeById(t) {
    return this.nodes.find(e => e.id === t) || null
  }
  addPath(t) {
    if (!this.idTracker.isAvailable(t.id)) throw Error("Duplicate id detected.")
    if (-1 !== t.id.indexOf("/")) throw Error('Path ids cannot have "/" character.')
    let e
    if (_(t)) {
      if (!(t.property in t.component.outputs)) throw Error(t.property + ' is not an "output" of the component')
      e = new OutputPath(t)
    } else if (m(t)) {
      if (!t.component.inputs || !(t.property in t.component.inputs)) throw Error(t.property + ' is not an "input" of the component')
      e = new InputPath(t)
    } else if (w(t)) {
      if (!(t.property in t.component.events)) throw Error(t.property + ' is not an "event" of the component')
      e = new EventPath(t)
    } else if (g(t)) {
      if (!t.component.emits || !(t.property in t.component.emits)) throw Error(t.property + ' is not an "emit" of the component')
      e = new EmitPath(t)
    } else if (t.type) throw Error("Couldn't determine path type")
    return this.idTracker.reserve(t.id), this.paths.set(t.id, Object.assign({}, t)), e
  }
  spyOnEvent(t) {
    const { path: e } = t,
      { node: i, component: n, type: s, property: r } = e
    if (m(e)) return n.inputs.onPropertyChanged(r, e => t.onEvent(e))
    if (_(e)) return n.outputs.onPropertyChanged(r, e => t.onEvent(e))
    if (g(e)) return this.eventBus.observe(new SceneObjectEventSpy(t))
    throw Error(`spy.path: ${h(i, n, s, r)}, is not a valid path to spy on`)
  }
  setValueAtPath(t, e) {
    vt.warn("`SceneObject.setValueAtPath` has been deprecated. Use `InputPath.set() instead.")
    const i = t.component.inputs
    i && t.property && t.property in i ? (i[t.property] = e) : vt.warn(`setValueAtPath called on component without input "${t.property}"`)
  }
  getValueAtPath(t) {
    vt.warn("`SceneObject.setValueAtPath` has been deprecated. Use `OutputPath.get() instead.")
    const e = t.component.outputs
    if (e && t.property && e[t.property]) return e[t.property]
    vt.warn(`getValueAtPath called on path that does not exist "${t.property}"`)
  }
}
class SceneObjectEventSpy {
  sceneObjectSpy: any
  src: any
  srcEventType: any
  targetEventType: any
  constructor(t) {
    ;(this.sceneObjectSpy = t), (this.src = t.path.component), (this.srcEventType = t.path.property), (this.targetEventType = t.path.property)
  }
  onEvent(t, e) {
    this.sceneObjectSpy.onEvent(e)
  }
}
function kt(t) {
  return !!t && !!("object" == typeof t && "x" in t && "y" in t && "z" in t && yt(t.x) && yt(t.y) && yt(t.z))
}
function At(t, e) {
  const { position: i, rotation: n, scale: s } = e,
    r = t.createNode()
  if (((r.name = e.name || "Unnamed Node"), i)) {
    if (!kt(i)) throw Error(`Invalid position ${JSON.stringify(i)}`)
    r.position.set(i.x, i.y, i.z)
  }
  if (n) {
    if (!kt(n)) throw Error(`Invalid rotation ${JSON.stringify(n)}`)
    r.quaternion.setFromEuler(new THREE.Euler((n.x * Math.PI) / 180, (n.y * Math.PI) / 180, (n.z * Math.PI) / 180, "YXZ"))
  }
  if (s) {
    if (!kt(s)) throw Error(`Invalid scale ${JSON.stringify(s)}`)
    r.scale.set(s.x, s.y, s.z)
  }
  for (const t of e.components) Ct(r, t)
  return r
}
function Ct(t, e) {
  const i = t.addComponent(e.type, e.inputs, e.id)
  if (i) {
    for (const t in e.events) i.events[t] = e.events[t]
    if (i.emits) for (const t in e.emits) i.emits[t] = e.emits[t]
  }
  return i
}
function St(t) {
  const e = new THREE.Euler()
  e.setFromQuaternion(t.quaternion, "YXZ")
  const i = 180 / Math.PI
  return {
    id: t.id,
    name: t.name,
    position: { x: t.position.x, y: t.position.y, z: t.position.z },
    rotation: { x: e.x * i, y: e.y * i, z: e.z * i },
    scale: { x: t.scale.x, y: t.scale.y, z: t.scale.z },
    components: Ut(t)
  }
}
function Ut(t) {
  const e = []
  for (const i of t.componentIterator()) {
    const t = {
      id: i.id,
      type: i.componentType,
      inputs: Object.assign({}, i.inputs),
      emits: {},
      events: {}
    }
    for (const e in i.emits) t.emits[e] = !!i.emits[e]
    for (const e in i.events) t.events[e] = !!i.events[e]
    e.push(t)
  }
  return e
}
var xt = {
  V_1_0: "1.0",
  V_2_0: "2.0",
  V_2_1: "2.1"
}

const Tt = (t, e, i) => {
    const n = new SceneObject(t, e),
      s = []
    for (const t of i.objects) {
      const e = jt(
        {
          createNode: function () {
            return n.addNode(t.id)
          }
        },
        t
      )
      s.push(e)
    }
    if (
      (i.bindings &&
        (function (t, e, i) {
          for (const i of e)
            if (2 === i.length) {
              const [e, n] = i,
                s = u(e, t),
                r = u(n, t)
              if (null === s.component || null === s.property) throw Error(`Could not resolve target for path '${e}'`)
              if (null === r.component || null === r.property) throw Error(`Could not resolve source for path '${n}'`)
              s.component.bind(s.property, r.component, r.property)
            }
        })(n, i.bindings),
      i.events &&
        (function (t, e, i) {
          for (const i of e)
            if (2 === i.length) {
              const [e, n] = i,
                s = u(e, t),
                r = u(n, t)
              if (null === s.component || null === s.property) throw Error(`Could not resolve target for path '${e}'`)
              if (null === r.component || null === r.property) throw Error(`Could not resolve source for path '${n}'`)
              s.component.bindEvent(s.property, r.component, r.property)
            }
        })(n, i.events),
      i.paths)
    )
      for (const t of i.paths) {
        const e = u(t[1], n)
        if (!(e.node && e.component && e.property && p(e.property, e.component))) throw Error(`Unable to parse path "${t[1]}"`)
        {
          const i = p(e.property, e.component)
          i &&
            n.addPath({
              id: t[0],
              type: i,
              node: e.node,
              component: e.component,
              property: e.property
            })
        }
      }
    return n
  },
  jt = (t, e) => {
    const i = e.position,
      n = e.scale,
      s = e.rotation,
      r = t.createNode(),
      a = e.name || "Unnamed Node"
    if (((r.name = a), i)) {
      if (!yt(i.x) || !yt(i.y) || !yt(i.z)) throw new Error(`Invalid position ${JSON.stringify(i)}`)
      r.position.set(i.x, i.y, i.z)
    } else r.position.set(0, 0, 0)
    if (s) {
      if (!yt(s.x) || !yt(s.y) || !yt(s.z)) throw new Error(`Invalid rotation ${JSON.stringify(s)}`)
      r.quaternion.setFromEuler(new THREE.Euler((s.x * Math.PI) / 180, (s.y * Math.PI) / 180, (s.z * Math.PI) / 180, "YXZ"))
    } else r.quaternion.set(0, 0, 0, 1)
    if (n) {
      if (!yt(n.x) || !yt(n.y) || !yt(n.z)) throw new Error(`Invalid scale ${JSON.stringify(n)}`)
      r.scale.set(n.x, n.y, n.z)
    } else r.scale.set(1, 1, 1)
    const o = []
    if (e.components)
      for (const t of e.components) {
        const e = Lt(r, t)
        e && o.push(e)
      }
    return (
      e.bindings &&
        (function (t, e, i) {
          for (const n of e)
            if (4 === n.length) {
              const [t, e, s, r] = n,
                a = i[t],
                o = i[s]
              if (!a) throw Error("could not find target Component index=" + t)
              if (!o) throw Error("could not find source Component index=" + s)
              a.bind(e, o, r)
            } else if (2 === n.length) {
              const [e, i] = n,
                s = c(e, t),
                r = c(i, t)
              if (null === s.component || null === s.property) throw Error(`Could not resolve target for path '${e}'`)
              if (null === r.component || null === r.property) throw Error(`Could not resolve source for path '${i}'`)
              s.component.bind(s.property, r.component, r.property)
            }
        })(r, e.bindings, o),
      e.events &&
        (function (t, e, i) {
          for (const n of e)
            if (4 === n.length) {
              const [t, e, s, r] = n,
                a = i[t],
                o = i[s]
              if (!a) throw Error("could not find target Component index=" + t)
              if (!o) throw Error("could not find source Component index=" + s)
              if (!(e in a.events)) throw Error("Component index=" + t + ' does not have "' + e + '" as a handled event')
              a.bindEvent(e, o, r)
            } else if (2 === n.length) {
              const [e, i] = n,
                s = c(e, t),
                r = c(i, t)
              if (null === s.component || null === s.property) throw Error(`Could not resolve target for event path '${e}'`)
              if (null === r.component || null === r.property) throw Error(`Could not resolve source for event path '${i}'`)
              s.component.bindEvent(s.property, r.component, r.property)
            }
        })(r, e.events, o),
      r
    )
  },
  Lt = function (t, e) {
    const i = t.addComponent(e.type, e.inputs, e.id)
    if (i) for (const t in e.events) i.events[t] = e.events[t]
    return i
  }
const Rt = (t, e, i) => {
    const n = JSON.parse(i)
    const s = n.version
    switch (s) {
      case xt.V_1_0:
        return ((t, e) => {
          const i = []
          for (const n of e.objects) {
            const e = jt(t, n)
            i.push(e)
          }
          return i
        })(t, n.payload)
      case xt.V_2_0:
        return Tt(t, e, n.payload)
      case xt.V_2_1:
        return (function (t, e, i) {
          const n = new SceneObject(t, e),
            s = []
          for (const t of i.objects) {
            const e = { createNode: () => n.addNode(t.id) }
            s.push(At(e, t))
          }
          const r = new Map(),
            a = new Map(),
            o = new Map(),
            l = new Map()
          for (const [t, e] of i.paths) {
            const i = u(e, n),
              { node: s, component: h, type: d, property: c } = i
            if (s && h && d && c) {
              const i = { id: t, node: s, component: h, property: c }
              switch (d) {
                case f.OUTPUT:
                  r.set(t, n.addPath(Object.assign(Object.assign({}, i), { type: d })))
                  break
                case f.INPUT:
                  a.set(t, n.addPath(Object.assign(Object.assign({}, i), { type: d })))
                  break
                case f.EVENT:
                  o.set(t, n.addPath(Object.assign(Object.assign({}, i), { type: d })))
                  break
                case f.EMIT:
                  l.set(t, n.addPath(Object.assign(Object.assign({}, i), { type: d })))
                  break
                default:
                  throw Error(`unable to parse path "${e}"`)
              }
            }
          }
          for (const [t, e] of i.bindings) {
            const i = a.get(t) || o.get(t)
            if (!i) throw Error(`"${t}" not found in input or event paths`)
            const s = r.get(e) || l.get(e)
            if (!s) throw Error(`"${t}" not found in output or emit paths`)
            n.bindPath(i, s)
          }
          return n
        })(t, e, n.payload)
      default:
        throw Error(`Unsupported scene version ${s}`)
    }
  },
  Ot = t => {
    const e = (function (t) {
      const e = { objects: [], bindings: [], paths: [] }
      for (const i of t.nodeIterator()) {
        const t = St(i)
        e.objects.push(t)
      }
      for (const [i, n] of t.bindings()) {
        const t = [i.id, n.id]
        e.bindings.push(t)
      }
      for (const i of t.pathIterator()) {
        const t = h(i.desc.node, i.desc.component, i.desc.type, i.desc.property)
        e.paths.push([i.desc.id, t])
      }
      return e
    })(t)
    return JSON.stringify({ version: xt.V_2_1, payload: e })
  }

class ComponentLoader {
  engine: any
  sceneModule: any
  queuedComponents: Set<unknown>
  started: boolean
  constructor(t, e) {
    ;(this.engine = t), (this.sceneModule = e), (this.queuedComponents = new Set()), (this.started = !1)
  }
  start() {
    ;(this.started = !0), this.addQueuedComponents()
  }
  addComponent(t) {
    this.started ? this.addToEngine(t) : this.queuedComponents.add(t)
  }
  removeComponent(t) {
    this.engine.removeComponent(this.sceneModule, t), this.queuedComponents.delete(t)
  }
  addQueuedComponents() {
    for (const t of this.queuedComponents) this.addToEngine(t)
  }
  addToEngine(t) {
    this.engine.addComponent(this.sceneModule, t)
  }
}
export default class SceneModule extends Module {
  componentFactory: ComponentBuilder
  eventBus: ComponentEventBus
  componentLoader: ComponentLoader
  renderer: any
  raycasterModule: any
  inputIni: any
  analytics: SceneAnalytics
  tags: Tags
  contextPropertyAccessor: TrackFirstPropertyAnalyticsWrapper
  componentStartAnalytics: TrackFirstKeyAnalytics
  constructor() {
    super(...arguments)
    this.name = "scene"
    this.componentFactory = new ComponentBuilder()
    this.eventBus = new ComponentEventBus()
  }
  async init(t, e) {
    let i, n, s
    this.componentLoader = new ComponentLoader(e, this)
    ;[i, this.renderer, this.raycasterModule, this.inputIni, n, s] = await Promise.all([
      e.getModule(AnalyticsModule),
      e.getModuleBySymbol(SymbolList.WEBGL_RENDERER),
      e.getModule(RaycasterModule),
      e.getModuleBySymbol(SymbolList.INPUT),
      e.market.waitForData(SdkData),
      e.getModule(NavigationModule)
    ])
    this.analytics = new SceneAnalytics(i, n)
    this.tags = new Tags()
    ;(function (t, e) {
      for (const t of B) {
        const e = Object.keys(t)
        for (const i of e) {
          const e = t[i],
            n = THREE
          if (i in n) {
            if ("object" == typeof e) for (const t in e) t in n[i] || (n[i][t] = e[t])
          } else n[i] = e
        }
      }
      THREE.DefaultLoadingManager.addHandler(/\.tga$/i, new TGALoader()),
        THREE.DefaultLoadingManager.addHandler(/\.jpe?g$/i, t()),
        THREE.DefaultLoadingManager.addHandler(/\.png$/i, e()),
        (THREE.Cache.enabled = !0)
    })(Q(this.renderer.cwfRenderer.renderer), it(this.renderer.cwfRenderer.renderer))
    this.registerFactory(OBJLoader2Component.factoryName, () => rt(OBJLoader2Component))
    this.registerFactory(FBXLoaderComponent.factoryName, () => rt(FBXLoaderComponent))
    this.registerFactory(ColladaLoaderComponent.factoryName, () => rt(ColladaLoaderComponent))
    this.registerFactory(GLTFLoaderComponent.factoryName, () => rt(GLTFLoaderComponent))
    this.registerFactory(ScrollingTube.factoryName, ScrollingTube.factory)
    this.registerFactory(TransformControlsComponent.factoryName, TransformControlsComponent.factory)
    this.registerFactory(LightsComponents.factoryName, LightsComponents.factory)
    this.registerFactory(PointLightComponent.factoryName, PointLightComponent.factory)
    this.registerFactory(DirectionalLightComponent.factoryName, DirectionalLightComponent.factory)
    this.registerFactory(AmbientLightComponent.factoryName, AmbientLightComponent.factory)
    this.registerFactory("mp.camera", ht(t.cameraPoseProxy))
    this.registerFactory("mp.input", wt(this.inputIni, s))
    this.registerFactory("mp.xr", bt(this.renderer.cwfRenderer.renderer))
    const a = t => {
      this.tags.tagObject(t.root, [G.Model])
      for (const e of t.floors) {
        this.tags.tagObject(e, [G.Floor])
        for (const e of t.rooms) this.tags.tagObject(e, [G.Room])
      }
      this.tags.tagObject(this.renderer.getScene().scene, [G.Scene])
    }
    e.market.waitForData(RoomMeshData).then(t => {
      a(t), t.onChanged(a)
    })
    this.contextPropertyAccessor = new TrackFirstPropertyAnalyticsWrapper(this.analytics)
    this.componentStartAnalytics = new TrackFirstKeyAnalytics(this.analytics)
  }
  registerFactory(t, e) {
    this.componentFactory.registerFactory(t, e)
  }
  createNode(t) {
    return (
      (t = t || new SceneObject(this, this.eventBus)),
      new SceneNode(
        this.componentLoader,
        this.renderer,
        this.raycasterModule.targets,
        this.componentStartAnalytics,
        this.componentFactory,
        t,
        this.eventBus,
        this.inputIni,
        this.contextPropertyAccessor,
        this
      )
    )
  }
  createObject() {
    return new SceneObject(this, this.eventBus)
  }
  startLoading() {
    this.componentLoader.start()
  }
  sceneTags() {
    return this.tags
  }
  serialize(t) {
    return Ot(t)
  }
  deserialize(t) {
    return Rt(this, this.eventBus, t)
  }
  get supportedSerializerVersions() {
    return xt
  }
  componentMap() {
    return {
      FBX_LOADER: FBXLoaderComponent.factoryName,
      DAE_LOADER: ColladaLoaderComponent.factoryName,
      OBJ_LOADER: OBJLoader2Component.factoryName,
      GLTF_LOADER: GLTFLoaderComponent.factoryName,
      SCROLLING_TUBE: ScrollingTube.factoryName,
      TRANSFORM_CONTROLS: TransformControlsComponent.factoryName,
      SIMPLE_LIGHTS: LightsComponents.factoryName
    }
  }
}
